简体   繁体   English

使用Sed在Bash脚本中搜索/替换变量

[英]Using Sed To Search/Replace Variable In Bash Script

I'm trying to change the date in the first line of a text file by using Sed to replace the previous days date with the current days date. 我正在尝试通过使用Sed将前几天的日期替换为当前日期的日期来更改文本文件第一行中的日期。

Below is the code from the bash script that I'm trying to use to accomplish this: 下面是我试图用来完成此操作的bash脚本中的代码:

YMD=$(date +%Y%m%d)

ODA=$(date -u +%Y%m%d --date="1 days ago")

mv ${HOMEDIR}/${PATH1}/nws_${VAR}_conus_daily_${ODA}.ctl ${HOMEDIR}/${PATH1}/nws_${VAR}_conus_daily_${YMD}.ctl

sed "s/${ODA}/${YMD}/" ${HOMEDIR}/${PATH1}/nws_${VAR}_conus_daily_${YMD}.ctl

URL1=http://water.weather.gov/${VAR}/p_download_new/${Y}/${M}/${D}/nws_${VAR}_conus_${YMD}.nc

wget -P ${HOMEDIR}/${PATH1}/ -N ${URL1}

The first line in the text file reads as follows: 文本文件的第一行内容如下:

dset ^grads/data/ahps/nws_precip_conus_20140423.nc

If you want sed to change your file, you have to give the -i option, like so: 如果要sed更改文件,则必须提供-i选项,如下所示:

sed -i "s/${ODA}/${YMD}/" ${HOMEDIR}/${PATH1}/nws_${VAR}_conus_daily_${YMD}.ctl

Otherwise sed will just output the changed file to standard output. 否则sed只会将更改后的文件输出到标准输出。

Use this: 用这个:

sed "1s/[0-9]\+\.nc/$(date +%Y%m%d).nc/" file.txt

It replace the numbers before .nc in the first line of file.txt with the output of 它将file.txt第一行中.nc之前的数字替换为

date +%Y%m%d

which outputs the current date in the desired format. 以所需的格式输出当前日期。


Proof of functionality : 功能证明

Having file.txt as this: 具有这样的file.txt

dset ^grads/data/ahps/nws_precip_conus_20140421.nc
bla bla 20140421.nc

Issue the above command: 发出以上命令:

sed "1s/[0-9]\+\.nc/$(date +%Y%m%d).nc/" file.txt

Output: 输出:

dset ^grads/data/ahps/nws_precip_conus_20140423.nc
bla bla 20140421.nc

You see that the date in the first line and only that has been replaced by the current date. 您会看到第一行中的日期,只有该日期已被当前日期替换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM