Awk is a powerful Linux command for string, text and file manipulation. It is used widely by Linux developers and system administrators all over the world for wide range of purposes. But by default, awk does not modify the input file used to perform its tasks. It displays the output directly to standard output (terminal). Sometimes, you may want to save these modifications in place. In this article, we will learn how to overwrite input file in Awk.
How to Overwrite Input File in Awk
Let us say you have the following awk command to extract certain text from /home/ubuntu/data.txt file.
awk -F, '{printf "%09d,%d\n" ,$1,$2}' /home/ubuntu/data.txt
When you run the above command, its output will be displayed in standard output (terminal). But it will not save the result to another or same input file.
Unfortunately, in system awk command, there is no direct option to overwrite the input file.
So what you need to do is to redirect the output to a temporary file and then use mv command to overwrite your input file using the temporary file.
$ awk -F, '{printf "%09d,%d\n" ,$1,$2}' /home/ubuntu/data.txt > tmp $ mv tmp /home/ubuntu/data.txt
You can combine the commands in a single line using && operator as shown below.
$ awk -F, '{printf "%09d,%d\n" ,$1,$2}' /home/ubuntu/data.txt > tmp && mv tmp /home/ubuntu/data.txt
Alternatively, you can also use another tool called GNU awk (gawk) which provides a direct option ‘-i inplace’ to overwrite input file. Here is its syntax.
gawk -i inplace -options 'script' file ...
You can use gawk to run the above mentioned command as shown below.
$ gawk -i inplace -F, '{printf "%09d,%d\n" ,$1,$2}' /home/ubuntu/data.txt
If your Linux has gawk (version > 4.10) already installed, it also supports awk command with -i inplace option.
$ awk -i inplace -F, '{printf "%09d,%d\n" ,$1,$2}' /home/ubuntu/data.txt
In this article, we have learnt how to overwrite input file in awk. You can run these commands directly on terminal or include them in your shell script.
Also read:
How to Read Command Line Arguments in NodeJS
How to Change Element’s Class in JavaScript
JavaScript Round to 2 Decimal Places
How to Disable Right Click Using JavaScript
How to Disable/Enable Input in jQuery
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.