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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…