Home > Enterprise >  How can I find and replace with bash and save the change to original file?
How can I find and replace with bash and save the change to original file?

Time:06-09

goal

  1. searching a file for the Version field
  2. only the first value labeled Version
  3. increments the value by 1

code

grep Version ./path/to/file | head -1 | awk -F. -v OFS=. '{$NF = 1 ; print}'

error

The intended change is made, but it is not saved. So I'm guessing I'll have to make a inline change? I know I can produce the file and merge it with the original, but I'd rather take a different approach. Any suggestions for improvement will be gratefully accepted.

CodePudding user response:

A combination of grep, head and awk is an antipattern. There is no need for grep and head, because awk has all the needed functionality.

That said, just follow this answer:

awk -i inplace -F. -v OFS=. \
    '!done && /Version/ {$NF  = 1; done = 1} 1' \
    ./path/to/file
  • Related