0

How do I replace a complex line in a file using sed?

For example I want replace a udev rule in /etc/udev/rules.d/70-persistent-net.rules.

This doesn't work:

OLD_RULE='SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="52:54:00:36:4c:e5", ATTR{type}=="1", KERNEL=="eth*", NAME="eth1"'

NEW_RULE='SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="52:54:00:36:4c:e5", ATTR{type}=="1", KERNEL=="eth*", NAME="eth0"'


sed -i "s/$OLD_RULE/$NEW_RULE/g" /etc/udev/rules.d/70-persistent-net.rules

The file remains unmodified.

2 Answers 2

1

You are going to need to escape all the characters in OLD_RULE that can be interpreted as pattern magic characters. Or more simply, use a pattern to match the line you want to operate on and then only perform the minimal replacement you actually need.

Something like (untested) sed -i '/, NAME="eth1"/s/eth1/eth0/' /etc/udev/rules.d/70-persistent-net.rules perhaps.

0

Something that might work sometimes (and that works here in this particular example) is to use printf's quoting ability and sed -r:

old_rule='SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="52:54:00:36:4c:e5", ATTR{type}=="1", KERNEL=="eth*", NAME="eth1"'
new_rule='SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="52:54:00:36:4c:e5", ATTR{type}=="1", KERNEL=="eth*", NAME="eth0"'
printf -v sed_repl 's/%q/%q/g' "$old_rule" "$new_rule"
sed -r -i "$sed_repl" /etc/udev/rules.d/70-persistent-net.rules

You must log in to answer this question.