paulhr
paulhr

Reputation: 377

awk sub() not doing replacement

The example text file.

in2.txt file:

*{commented out line}* KeyWordName = KeyWordValueAA  
KeyWordName = KeyWordValueAA

The regexp finds the string:

awk '/^KeyWordName[[:blank:]]=[[:blank:]].*$/' in2.txt

Output:

KeyWordName = KeyWordValueAA

Command that results in no errors or changed text:

awk '{sub(/^KeyWordName[[:blank:]]=[[:blank:]].*$/, "KeyWordValueBB")}' in2.txt

Removing the double quotes does not work either. Reading the manpage did not help either.

Upvotes: 0

Views: 647

Answers (1)

jas
jas

Reputation: 10865

You need to explicitly print to see any output:

A common awk idiom is to add a 1 after the action:

$ awk '{sub(/^KeyWordName[[:blank:]]=[[:blank:]].*$/, "KeyWordValueBB")}1' file
{commented out line} KeyWordName = KeyWordValueAA
KeyWordValueBB

The 1 is an always-true pattern and since there's no corresponding action, the default action of print is performed (on all input lines).

Or you can just use print:

$ awk '{sub(/^KeyWordName[[:blank:]]=[[:blank:]].*$/, "KeyWordValueBB")} {print}' file
{commented out line} KeyWordName = KeyWordValueAA
KeyWordValueBB

To change the file when you don't have the -i option, save to a temporary file and rename it to your file (that's what -i is doing for you, anyway). By using && we are sure the mv command will only be executed if the awk terminates with success. Stil, you might want to save a copy of your original file first in case the awk is "successful" from the OS point of view, but doesn't do what you expected!

awk '{ ... }' file > tmp && mv tmp file

Upvotes: 1

Related Questions