Redirecting to the same output file as input file like:
awk '!seen[$0]++' .gitignore > .gitignore
will end with an empty file. This is because using the >
operator, the shell will open and truncate the file before the command get's executed. Meaning you'll lose all your data.
With newer versions of GNU awk you can use the -i inplace
option to edit the file in place:
awk -i inplace '!seen[$0]++' .gitignore
If you don't have a recent version of GNU awk, you'll need to create a temporary file:
awk '!seen[$0]++' .gitignore > .gitignore.tmp
mv .gitignore.tmp .gitignore
Another alternative is to use the sponge
program from moreutils
:
awk '!seen[$0]++' .gitignore | sponge .gitignore
sponge
will soak all stdinput and open the output file after that. This effectively keeps the input file intact before writing to it.