Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change a line with awk

Tags:

bash

awk

Im trying to make a substitution of a single line in a file with awk, for example

changing this:

e1 is (on)

e2 is (off)

to:

e1 is (on)

e2 is (on)

use command:

awk '/e2/{gsub(/off/, "on")};{print}' ~/Documents/Prueba > ~/Documents/Prueba

this makes the substitution but the file ends blank!

like image 453
Josepas Avatar asked Feb 29 '12 16:02

Josepas


People also ask

Can awk edit in place?

Overview. Both the awk command and the sed command are powerful Linux command-line text processing utilities. We know that the sed command has a handy -i option to edit the input file “in-place”. In other words, it can save the changes back to the input file.

How do you replace a line in a file with sed?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace.

How do I print 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.


2 Answers

Another answer, using a different tool (sed, and the -i (in place) flag)

sed -i '/e2/ s/off/on/' ~/Documents/Prueba
like image 52
David Souther Avatar answered Sep 29 '22 03:09

David Souther


Your awk is correct, however you are redirecting to the same file as your original. This is causing the original file to be overwritten before it has been read. You'll need to redirect the output to a different file.

awk '/e2/{gsub(/off/, "on")};{print}' ~/Documents/Prueba > ~/Documents/Prueba.new

Rename Prueba.new afterwards if necessary.

like image 29
qbert220 Avatar answered Sep 29 '22 05:09

qbert220