2017-08-30 65 views
-2

我有一個for循環遞歸搜索目錄中的文件。從字符串路徑檢索日期

for FILE in $(find /home/mydir/ -name '*.txt' -or -name '*.zip') 

它們具有以下格式:

/home/mydir/subdir1/subdir2/22280317.txt 

我想提取離開.txt的作爲格式2017-03-28之日起6個號碼我已經用awk試過不過我有麻煩,因爲是我想忽略的兩位數字

回答

1

這可能會解決你的問題

find -name "*.txt" -exec sh -c 'f=${0%.txt}; l6=${f: -6}; date -d "${l6: -2}-${l6:2:2}-${l6:0:2}" +"%Y-%m-%d" ' {} \; 

測試結果

# create sample files 
[[email protected] test]$ touch 10280317.txt 
[[email protected] test]$ touch 10170317.txt 
[[email protected] test]$ touch 10170398.txt 

# files created 
[[email protected] test]$ ls *.txt 
10170317.txt 10170398.txt 10280317.txt 

# output using date command which takes care of year 
# remove .txt 
# extract last 6 char 
# input year-mon-date to date command 
[[email protected] test]$ find -name "*.txt" -exec bash -c 'f=${0%.txt}; l6=${f: -6}; date -d "${l6: -2}-${l6:2:2}-${l6:0:2}" +"%Y-%m-%d" ' {} \; 
2017-03-28 
2017-03-17 
1998-03-17 

在情況下,如果你想與日期,那麼

[[email protected] tmp]$ pwd 
/tmp 

[[email protected] tmp]$ find -name "*.txt" -exec bash -c 'f=${0%.txt}; l6=${f: -6}; echo $f $(date -d "${l6: -2}-${l6:2:2}-${l6:0:2}" +"%Y-%m-%d") ' {} \; 
./tss/test/10280317 2017-03-28 
./tss/test/10170317 2017-03-17 
./tss/test/10170398 1998-03-17 
一起顯示文件名
0

With sed表達式:

find /home/mydir/ -name '*.txt' -or -name '*.zip' | sed -E 's/.*([0-9]{2})([0-9]{2})([0-9]{2})\.txt/20\3-\2-\1/' 
0

假設該文件是相同的格式(22280317.txt)命名爲永諾,這是我的解決方案:

awk -v FPAT="([0-9]{2})" 'BEGIN{ FS = "/"; OFS = "-" }{ x = substr($NF, 3, 6); if (patsplit(x, a)) print a[1], a[2], "20"a[3] }' 

打印:

28-03-2017