2011-04-21 171 views
2

我有一個字符串ABCD20110420.txt,我想從中提取日期。預計2011-04-20 我可以使用替換刪除文本部分,但我如何插入「 - 」?從字符串中提取數字

# echo "ABCD20110420.txt" | replace 'ABCD' '' | replace '.txt' '' 
20110420 

回答

4

echo "ABCD20110420.txt" | sed -e 's/ABCD//' -e 's/.txt//' -e 's/\(....\)\(..\)\(..\)/\1-\2-\3/'

閱讀:sed FAQ

4

只需使用shell(bash)的上述

$> file=ABCD20110420.txt 
$> echo "${file//[^0-9]/}" 
20110420 
$> file="${file//[^0-9]/}" 
$> echo $file 
20110420 
$> echo ${file:0:4}-${file:4:2}-${file:6:2} 
2011-04-20 

適用於喜歡你的示例文件。如果您有像A1BCD20110420.txt這樣的文件,則無法使用。

對於這種情況,

$> file=A1BCD20110420.txt  
$> echo ${file%.*} #get rid of .txt 
A1BCD20110420 
$> file=${file%.*} 
$> echo "2011${file#*2011}" 
20110420 

或者你可以使用正則表達式(擊3.2+)

$> file=ABCD20110420.txt 
$> [[ $file =~ ^.*(2011)([0-9][0-9])([0-9][0-9])\.*$ ]] 
$> echo ${BASH_REMATCH[1]} 
2011 
$> echo ${BASH_REMATCH[2]} 
04 
$> echo ${BASH_REMATCH[3]} 
20 
0
$ file=ABCD20110420.txt 
$ echo "$file" | sed -e 's/^[A-Za-z]*\([0-9][0-9][0-9][0-9]\)\([0-9][0-9]\)\([0-9][0-9]\)\.txt$/\1-\2-\3/' 

這隻需要一個sed的調用。

1
echo "ABCD20110420.txt" | sed -r 's/.+([0-9]{4})([0-9]{2})([0-9]{2}).+/\1-\2-\3/' 
0
echo "ABCD20110420.txt" | sed -r 's/.{4}(.{4})(.{2})(.{2}).txt/\1-\2-\3/'