Ubuntu: AWK command executed with out error but not modifying the file


I am applying awk command on a file but this file is not modifying. can any one suggest why this is happening?

awk 'BEGIN{FS=OFS=""}; {if($692=="6") sub($690,"9");print $0;}' abc.txt >efg.txt  

Note: each line contains around 1000 characters.


What is wrong

The key issue is that you're using sub() incorrectly. sub() is supposed to substitute based on pattern match (that's the important part!). Proper syntax is:


What you're doing is sub($692,"9"), so you're telling it to replace first occurrence of the same thing that you see in field number 692, but that first occurrence may be way way way before in the line.

Here's an example:

$ echo "1253456" | awk 'BEGIN{FS=OFS=""};{if($4==3) sub($6,"@");print}'                                                                                 12@3456  

This literally takes whatever in the 6th field (which is number 5) and removes first occurrence of that thing. Same as what your command was doing.

What should actually be done

To replace a specific field, you don't need sub(), just assign to the field directly.

awk 'BEGIN{FS=OFS=""}; {if($692==6) $690="9";print}' abc.txt >efg.txt  

Notice that I also removed $0 from print because calling print itself already assumes $0 by default

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »