0

As a follow up to this question - grep and awk, combine commands?

Using a command such as

awk '/^-/{ print $9 }' file > outputfile

How can I awk a file and have the output redirected to the same file name?

I tried

awk '/^-/ {print $9}' outfile.log >outfile.log

..but the resulting outfile.log comes up empty.

alexherm
  • 1,362
  • 2
  • 18
  • 31
  • 4
    Possible duplicate of [Save modifications in place with awk](https://stackoverflow.com/questions/16529716/save-modifications-in-place-with-awk) – Inian Jun 19 '19 at 17:38

1 Answers1

3

You are probably looking for in-place edit for modifying the same file as mentioned in the duplicate. Your attempt could never work, awk .. file > file because the shell processes the re-directions even before running the actual command, so > file actually truncates the file, because of an empty re-direction. So the awk could never see the value of $9 in the file.

You probably need mktemp which creates a random filename string under a temporary path in your filesystem. You could re-direct the command output to such a file and move it back to the original file

awk '/^-/ {print $9}' outfile.log >tmpfile && mv tmpfile outfile.log

Using mktemp would resolve a potential overwrite/deletion of file if you have a filename tmpfile in your current directory.

tmpfile="$(mktemp)"
awk '/^-/ {print $9}' outfile.log > "$tmpfile" && mv "$tmpfile" outfile.log

If you use GNU awk, you can write

gawk -i inplace '...' file

This is documented in the gawk manual.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
Inian
  • 80,270
  • 14
  • 142
  • 161