linux - [Solved-5 Solutions] Awk save modifications in place - ubuntu - red hat - debian - linux server - linux pc



Linux - Problem :

If there is an option to write changes to file, similar to sed where you would use -i option to save modifications to a file.

You could use redirection to write changes. However is there an option in awk to do that?

Linux - Solution 1:

In latest GNU Awk , it has the option of "inplace" file editing:

The "inplace" extension, built using the new facility, can be used to simulate the GNU "sed -i" feature.

Example usage:

$ gawk -i inplace '{ gsub(/foo/, "bar") }; { print }' file1 file2 file3
click below button to copy the code. By - Linux tutorial - team

To keep the backup:

$ gawk -i inplace -v INPLACE_SUFFIX=.bak '{ gsub(/foo/, "bar") }
> { print }' file1 file2 file3
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 2:

Unless you have GNU awk 4.1.0

You won't have such an option as sed's -i option so instead do:

$ awk '{print $0}' file > tmp && mv tmp file
click below button to copy the code. By - Linux tutorial - team

Note: The -i is not magic, it is also creating a temporary file sed just handles it for you.

As of GNU awk 4.1.0

The new -i option (from xgawk) is used for loading awk library files. This differs from -f in that the first non-option argument is treated as a script.

You need to use the bundled inplace.awk include file to invoke the extension properly like so:

$ cat file
123 abc
456 def
789 hij

$ gawk -i inplace '{print $1}' file

$ cat file
123
456
789
click below button to copy the code. By - Linux tutorial - team

The variable INPLACE_SUFFIX can be used to specify the extension for a backup file:

$ gawk -i inplace -v INPLACE_SUFFIX=.bak '{print $1}' file

$ cat file
123
456
789

$ cat file.bak
123 abc
456 def
789 hij
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 3:

someprocess < file > file
click below button to copy the code. By - Linux tutorial - team
  • The shell performs the redirections before handing control over to someprocess (redirections).
  • The > redirection will truncate the file to zero size (redirecting output). Therefore, by the time someprocess gets launched and wants to read from the file, there is no data for it to read.

Linux - Solution 4:

echo "$(awk '{awk code}' file)" > file
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 5:

echo "$(awk '{awk code}' file)" > file
click below button to copy the code. By - Linux tutorial - team

Related Searches to - linux - linux tutorial - awk save modifications in place