Sed 从字符串中提取数字

Sed 从字符串中提取数字,sed,awk,grep,Sed,Awk,Grep,我有一个字符串ABCD20110420.txt,我想从中提取日期。预计2011-04-20 我可以使用replace删除文本部分,但是如何插入“-”呢 只需使用shell(bash) 以上内容适用于像您的示例这样的文件。如果您有像A1BCD20110420.txt这样的文件,则将无法工作 那么, $> file=A1BCD20110420.txt $> echo ${file%.*} #get rid of .txt A1BCD20110420 $> file=${fi

我有一个字符串ABCD20110420.txt,我想从中提取日期。预计2011-04-20 我可以使用replace删除文本部分,但是如何插入“-”呢

只需使用shell(bash)

以上内容适用于像您的示例这样的文件。如果您有像
A1BCD20110420.txt这样的文件,则将无法工作

那么,

$> file=A1BCD20110420.txt    
$> echo ${file%.*} #get rid of .txt
A1BCD20110420
$> file=${file%.*}
$> echo "2011${file#*2011}"
20110420
也可以使用正则表达式(Bash 3.2+)

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

阅读:

这只需要对sed进行一次调用

echo "ABCD20110420.txt" | sed -r 's/.+([0-9]{4})([0-9]{2})([0-9]{2}).+/\1-\2-\3/'
$> file=A1BCD20110420.txt    
$> echo ${file%.*} #get rid of .txt
A1BCD20110420
$> file=${file%.*}
$> echo "2011${file#*2011}"
20110420
$> 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
$ 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/'
echo "ABCD20110420.txt" | sed -r 's/.+([0-9]{4})([0-9]{2})([0-9]{2}).+/\1-\2-\3/'
echo "ABCD20110420.txt" | sed -r 's/.{4}(.{4})(.{2})(.{2}).txt/\1-\2-\3/'