使用 sed 用变量替换正则表达式 [英] Use sed to replace regex with a variable
本文介绍了使用 sed 用变量替换正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个 bash 脚本,我可以在其中将文件名中的日期替换为当前日期,但是,我无法这样做.
I'm trying to create a bash script where I can replace a date in a filename with the current date, however, I'm not being able to do so.
这是我目前所拥有的:
#!/bin/bash
my_file="FILENAME_20170410235908_GTT_DEV_20170410235400_20170410235408_XX_YY.nc"
my_date=`date "+%Y%m%d"`
echo "$my_file" | sed 's/\([0-9]\{12\}\)/"${my_date}"/g'
我目前得到这个:
FILENAME_"${my_date}"08_GTT_DEV_"${my_date}"00_"${my_date}"08_XX_YY.nc
但是,这就是我想要的:
Howerver, this is what I'd like to have:
FILENAME_2019070135908_GTT_DEV_20190701235400_20190701235408_XX_YY.nc
我怎样才能做到这一点?
How can I achieve this?
推荐答案
你可以试试
sed "s/\([0-9]\+\)/${my_date}/g"
单引号不会替换可变数据.my_date
将只有日期.如果您还需要时间戳,请从 date 命令添加它.
single quote will not replace variable data.
my_date
will have only date. If you want the timestamp also, add it from the date command.
这篇关于使用 sed 用变量替换正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文