3

I need to overwrite some configs on many servers at once and I want to modify the origianl config file while creating a backup, can all that be done with sed, just for curiosity?

Someone was mentioning this pattern, but it doesn't work.

new_port="..."
sed -i .bak "s/port=2334/${new_port}/g"
1
  • As there is an answer already I will only suggest to look for "perl pie" - it should be equally good.
    – DevilaN
    Nov 25, 2021 at 8:56

2 Answers 2

8
sed -i .bak "s/port=2334/${new_port}/g"

is nearly what you’re looking for; the fix is to remove the space after -i:

sed -i.bak "s/port=2334/${new_port}/g"

If new_port only has the port number, you’ll also have to repeat port=:

sed -i.bak "s/port=2334/port=${new_port}/g"

All of this only works if you actually specify the names of the files to be processed, after the sed expression.

0
0

Tried with awk

awk '{print $0}' file >file.backup && awk '{gsub(/port=2334/,"port=${new_port}",$0);print }' file >tmpfile && mv tmpfile file
1
  • Just because something can be done in AWK doesn’t mean it’s a good idea to do it... Your first invocation is a slow cp, why not use that? Nov 25, 2021 at 22:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .