3

I need to change

- FROM

Car
Bus

- TO

Helicopter
Airplane

This two commands are sufficient.

awk -i inplace '{sub(/Car/,"Helicopter")}1' file
awk -i inplace '{sub(/Bus/,"Airplane")}1' file

And this command is sufficient too.

sed -e 's/Car/Helicopter/' \
    -e 's/Bus/Airplane/' \
    -i file

In "awk" is it possible to combine two operations in one command like "sed".

Thanks in advance!

  • 1
    awk -i inplace '{sub(/Car/,"Helicopter")} {sub(/Bus/,"Airplane")}1' file did not work? – Alex Stragies Jan 6 '17 at 9:28
  • 1
    @AlexStragies This is the expected answer, I believe – xhienne Jan 6 '17 at 9:55
1

Try it like this:

awk -i inplace '{sub(/Car/,"Helicopter")} {sub(/Bus/,"Airplane")}1' file

Now you have 3 Condition {Action} blocks. 1 is a special case of a condition {action} block.

Or try this:

awk -i inplace '{sub(/Car/,"Helicopter") ; sub(/Bus/,"Airplane")}1' file

, because an action block can have more than one statement.

  • This works as long as the later substitutions do not substitute something already processed by an earlier substitution. Take as an example changing goods into cargo and then car into automobile. – Kusalananda Jan 6 '17 at 11:42
0
awk -i inplace '
    /^Car$/ { print "Helicopter"; next }
    /^Bus$/ { print "Airplane";   next }
            { print }' file

By matching against the complete line (using the ^ and $ anchors), we make sure that we don't match the strings as substrings in other lines (e.g. the Car in Cart). By acting on the found line and then immediately executing next we protect from changing a line into something that might trigger a later pattern.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.