-2

i'm trying to overwrite the contents of a file with the output an awk substitution. below is the substitution that i am using.

awk '{ "sub(/string/, /newstring/)" } file' 

i have tried variations of print and echo using | and > and whilst i know the command itself works i cannot understand how to make use of the output.

awk 'BEGIN { print "sub(/string/, /newstring/)"; > "file" }' file 

this only prints the contents of the ""

awk 'BEGIN { print ${sub(/string/, /newstring/)}; > "file" }' file 

this provides syntax errors

awk 'BEGIN { print "${sub(/string/, /newstring/)}" > "file" }' file

this only prints the "" again

  • `awk '{sub(/string/, "newstring")}1' file > tmp && mv tmp file` I believe is what you are looking for. That `awk` has a little short-hand in it. You could also do the more verbose way `awk '{sub(/string/, "newstring"); print $0}'`. I don't believe you can write out to the same file you are reading with `> "file"` so the `tmp` file is necessary. That being said, I believe `gawk` has an inplace option like `sed` does with the `-i inplace` flag. – JNevill May 06 '22 at 15:24
  • 1
    This question has all the answers: https://stackoverflow.com/questions/16529716/save-modifications-in-place-with-awk – James Brown May 06 '22 at 15:29

0 Answers0