我有一个字符串ABCD20110420.txt,我想从中提取日期。预计2011-04-20 我可以使用替换删除文本部分,但我如何插入“ - ”?从字符串中提取数字
# echo "ABCD20110420.txt" | replace 'ABCD' '' | replace '.txt' ''
20110420
我有一个字符串ABCD20110420.txt,我想从中提取日期。预计2011-04-20 我可以使用替换删除文本部分,但我如何插入“ - ”?从字符串中提取数字
# echo "ABCD20110420.txt" | replace 'ABCD' '' | replace '.txt' ''
20110420
echo "ABCD20110420.txt" | sed -e 's/ABCD//' -e 's/.txt//' -e 's/\(....\)\(..\)\(..\)/\1-\2-\3/'
阅读:sed FAQ
只需使用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
$ 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的调用。
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/'