Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write finding output to same file using awk command

Tags:

bash

shell

awk

awk '/^nameserver/ && !modif { printf("nameserver 127.0.0.1\n"); modif=1 } {print}' testfile.txt 

It is displaying output but I want to write the output to same file. In my example testfile.txt.

like image 786
Venkat Avatar asked Nov 05 '11 10:11

Venkat


People also ask

How do I print the same line in awk?

To print a blank line, use print "" , where "" is the empty string. To print a fixed piece of text, use a string constant, such as "Don't Panic" , as one item. If you forget to use the double-quote characters, your text is taken as an awk expression, and you will probably get an error.

How do you assign a Output command to awk variable?

Use command substitution to assign the output of a command to a variable. The syntax is: var1=$(command) . Show activity on this post. The awk command needs to have some input!

What is awk '{ print $1 }'?

If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.


2 Answers

Not possible per se. You need a second temporary file because you can't read and overwrite the same file. Something like:

awk '(PROGRAM)' testfile.txt > testfile.tmp && mv testfile.tmp testfile.txt 

The mktemp program is useful for generating unique temporary file names.

There are some hacks for avoiding a temporary file, but they rely mostly on caching and read buffers and quickly get unstable for larger files.

like image 58
thiton Avatar answered Sep 22 '22 16:09

thiton


Since GNU Awk 4.1.0, there is the "inplace" extension, so you can do:

$ gawk -i inplace '{ gsub(/foo/, "bar") }; { print }' file1 file2 file3 

To keep a backup copy of original files, try this:

$ gawk -i inplace -v INPLACE_SUFFIX=.bak '{ gsub(/foo/, "bar") } > { print }' file1 file2 file3 

This can be used to simulate the GNU sed -i feature.

See: Enabling In-Place File Editing

like image 38
kenorb Avatar answered Sep 21 '22 16:09

kenorb