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!

Sabrina
  • 31
  • 1
  • 2

2 Answers2

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.

Alex Stragies
  • 5,857
  • 2
  • 32
  • 56
  • 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 06 '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.

Kusalananda
  • 320,670
  • 36
  • 633
  • 936