0

I am writing a bash script, and in that bash script I have a line similar to this:

awk '/TextToBeMatched/ { print; print "TextToInsert"; next }1' "/Path/to/specified/file.extension"

And currently what it does is finds "TextToBeMatched" in the specified file, and then replaces it with "TextToInsert". But I would like it to instead of then printing the output to the console session, I would like it to print to a file, I guess that I would do this with output redirection, so how exactly would I do this?

I read about output redirection with awk here, but it was not so much help with my code.

  • awk >/path/to/output '/Tex...? – muru Mar 21 '15 at 19:54
  • @muru: I just get awk: 1: unexpected character '.' then. – user364819 Mar 21 '15 at 20:08
  • 1
    then it's decidedly odd, since the redirection in my command is done by the shell and awk shouldn't be aware of it. – muru Mar 21 '15 at 20:11
  • 1
    -i needs GNU awk, so: gawk -i inplace '/T...'. – muru Mar 21 '15 at 20:25
  • 2
    If you need help with commands, you need to post the command and any errors you get – Panther Mar 21 '15 at 21:05
1

To save the output of awk to a file, simply use redirection:

awk > /path/to/output/file ...

Since the shell handles the redirection and empties the output file, you cannot use the same file for both input and output - by the time awk gets to it, the file would have been truncated by the shell.

With GNU awk, you can use the in-place editing plugin to save the output to the same file:

gawk -i inplace ... 

This works much the same way sed -i does.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy