alexherm
alexherm

Reputation: 1362

awk to update existing file

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.

Upvotes: 0

Views: 1158

Answers (1)

Inian
Inian

Reputation: 85560

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.

Upvotes: 3

Related Questions