Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

bash - Use sed to replace regex with a variable

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.

Here's what I have so far:

#!/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'

I'm currently getting this:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can try

sed "s/([0-9]+)/${my_date}/g"

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...