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!
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.
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.
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.
Another answer, using a different tool (sed, and the -i (in place) flag)
sed -i '/e2/ s/off/on/' ~/Documents/Prueba
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With