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
191 views
in Technique[技术] by (71.8m points)

bash - How can I replace unknown values in known positions in a line?

I have one solution to the specific problem I faced, but it is quite hacky and not at all portable:

crontab -l > my-crontab
command='~/test.sh'
minute=1
hour=2
sed -i 's#[0-9]+ [0-9]+ [*]+ [*]+ [*]+ '"$command"'#'"$minute"' '"$hour"' * * * '"$command"'#g' my-crontab
crontab my-crontab

If I have a line in my crontab that reads, for example, 61 25 * * * ~/test.sh, the above solution will correctly replace that entire line with 1 2 * * * ~/test.sh, where I have of course hard-coded the format of the entire line.

More generally, then, how can I find any line that contains a known string in an unknown position and then only replace the first two columns of that line?

Test case: my-crontab contains many lines and at least one of them looks like one of these:

61 25 (gibberish of unknown format that contains the string ~/test.sh and more)
* 25 (gibberish of unknown format that contains the string ~/test.sh and more)
61 * (gibberish of unknown format that contains the string ~/test.sh and more)

A working general solution will find any line containing string ~/test.sh and replace the first two columns:

1 2 (gibberish of unknown format that contains the string ~/test.sh and more)

I have accepted an answer below using sed and extended regex, but I would still be interested to learn of a solution making use of awk column syntax, i.e. $1 $2

question from:https://stackoverflow.com/questions/66051251/how-can-i-replace-unknown-values-in-known-positions-in-a-line

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

1 Reply

0 votes
by (71.8m points)

Use a pattern before the s command to restrict it to just lines that match that pattern.

Then only replace the beginning of the line in the s/// command.

crontab -l > my-crontab
command='~/test.sh'
minute=1
hour=2
sed -i -r "\#$command#s#^([^[:space:]]+[[:space:]]+[^[:space:]]+)#$minute $hour#gm" my-crontab
crontab my-crontab

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

...