Reputation: 31
I have a line in a file as shown below
abcd x 10.10.10.10
sometimes the same line might have some extra fields like below
abcd 123 AB x 10.10.10.10
So now I have to delete this line from the file. My match pattern would be to search for abcd, x and 10.10.10.10 in a line and delete it as these are the only fixed values. Is there way to match multiple patterns with logical and in sed and delete the line? I have tried using regex, but since the pattern is not always the same here, that does not work. I need a solution with sed. I tried to search other websites and stackoverflow. Could not find any solution which works for me.
Upvotes: 1
Views: 196
Reputation: 58578
This might work for you (GNU sed);
sed -r 'h;s/$/\nabcd x 10.10.10.10/;ta;:a;s/(.+)(.*\n.*)\<\1\>/\2/;ta;/^\s*\n\s*$/d;x' file
This makes a copy of the current line. Then appends the required fields to the end of the line separated by a newline. Using substitution and backreferences, matching fields are removed from the pattern space until no further matches can be made. If the remaining string consists of nothing but zero or more spaces separated by a newline this would identify a line to be deleted, otherwise the line is to be kept so the copy is reinstated.
Upvotes: 0
Reputation: 204721
This is a job for awk, not sed:
$ cat tst.awk
BEGIN {
split("abcd x 10.10.10.10",flds)
for (idx in flds) {
targets[flds[idx]]
}
}
{
delete cnt
for (i=1;i<=NF;i++) {
cnt[$i]++
}
for (fld in targets) {
if (cnt[fld] == 1) {
delete cnt[fld]
}
}
for (fld in cnt) {
# If we reach here then one or more of these conditions is true:
# a) there was a field that is not one we targetted
# b) there was a target field that occurred multiple times
# c) a target field was missing
print
next
}
}
$ awk -f tst.awk file
abcd 123 AB x 10.10.10.10
Since awk is available on all UNIX installations just like sed is, there's no reason to force yourself to try to use sed for this.
Upvotes: 2