user3017748
user3017748

Reputation: 155

want to delete ith matching pattern from file

i want to delete the static entry from dhcpd.cong file by using shell command. Currently I am using sed for the hostname. But there are multiple static entries for same hostname. here is the portion from sample dhcpd.conf file:

host my-system4 {
  hardware ethernet 11:22:33:44:55:66;
  fixed-address 192.168.17.54;
}

host my-system4 {
  hardware ethernet 22:33:44:55:66:77;
  fixed-address 192.168.17.34;
}

Here i used:

sed -i '/host my-system4/,/^\}/d' xyz.txt

But this command is deleting all the host my-system4 entries from file. How can I delete the specific entry by doing grep on fixed-address. Also the number of lines under host my-system4 may also vary. I nee shell command which do grep on fixed-address and delete only that specific host entry.

Upvotes: 3

Views: 115

Answers (2)

devnull
devnull

Reputation: 123668

You could say:

sed -e :a -e '/host my-system4/,/}/ { /}/!{ $!{N;ba};};/pattern/d;}' filename

to delete the entry containing the specified pattern.

For example,

sed -e :a -e '/host my-system4/,/}/ { /}/!{ $!{N;ba};};/192\.168\.17\.34/d;}' filename

would delete the entry containing the fixed address 192.168.17.34. Note that . has been escaped so as to match a literal ..


If the entries in the file are guaranteed to be separated by a blank line, you could simplify it by saying:

sed -e '/./{H;$!d;}' -e 'x;/pattern/d' filename

where the pattern in the command above denotes the entry to be deleted.


Add the -i option for in-place editing:

sed -i -e :a -e '/host my-system4/,/}/ { /}/!{ $!{N;ba};};/192\.168\.17\.34/d;}' filename

or

sed -i -e '/./{H;$!d;}' -e 'x;/pattern/d' filename

Upvotes: 3

Birei
Birei

Reputation: 36282

One solution using .

vim -u NONE -N \
    -c 'set backup | g/\vfixed-address\s+192\.168\.17\.34/ normal dap' \
    -c 'x' infile

It creates a backup of the file appending ~ to the name. Remove set backup and the pipe if you want to risk yourself to lose data. It uses a global replacement to search the line fixed-address 192.168.17.34 and selects the whole paragraph to delete it. The last x command saves the modified file.

Upvotes: 1

Related Questions