Script to swap place string with another string

Asked

Viewed 97 times

1

I have the file /etc/udev/rules.d/70-persistent-net.rules that have such interfaces:

SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="1c:af:f7:e7:a4:3c", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth0"
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="78:e3:b5:43:47:ad", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth1"

I want to replace the eth0 with the eth1 and vice versa, tried to do with sed command unsuccessfully:

sed -i 's|eth0|eth1|g' 

he exchanges the eth0 for eth1 obviously but now I have 2 interfaces eth1.

I wanted a command that "changes" the Strings of place, to get this result:

SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="1c:af:f7:e7:a4:3c", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth1"
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="78:e3:b5:43:47:ad", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth0"
  • You’ll always have only two lines?

  • no.. It was just by example same...

1 answer

3


You cannot change A with B in one step. You need to use a temporary value:

A  -> XX
B  -> A
XX -> B

In this case:

sed -e 's/eth0/ethXX/g' -e 's/eth1/eth0/g' -e 's/ethXX/eth1/g'

Returns:

SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="1c:af:f7:e7:a4:3c", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth1"
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="78:e3:b5:43:47:ad", ATTR{dev_id}=="0x0", ATTR{type}=="1", KERNEL=="eth*", NAME="eth0"
  • Hmm got it, thanks for the answer! I also found this topic here http://stackoverflow.com/questions/23758321/how-to-swap-two-strings-in-file-using-bash which does the same with the sed and perl command .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.