sans sans - 6 months ago 10
Bash Question

I got the query to search a line for a pattern using sed?

Search each line of a file for a pattern and if pattern exists in a file, search whether the very next line starts and ends with the same pattern. If yes, delete the line.

input is like:

abd dgf & dhdj
& hjsdhkl kjk &
dfjhfjkk
fjdfhjf &
sdhjgfsdg
& dghdf &
hfjsdhj


the ouput will be like this:

abd dgf & dhdj

dfjhfjkk
fjdfhjf &
sdhjgfsdg
& dghdf &
hfjsdhj


Here
'&'
is my pattern. I used several options with sed. But none of them gives me correct output.
i used var=
sed -n "/$1/{n;p}" $2 | grep "^$1" | grep "$1$"


sed -i "/^$var$/d" $2 .but it won't work.

Answer

In regards to

search whether the very next line starts and ends with the same pattern. If yes, delete the line.

Do you mean that in the same way that uniq does? If so, you're welcome. Though I don't see that as the implication in your example.

Do you need to use sed?
If not then what about:

$ perl -nE\
'if($follows_match && /^\&/ && /\&$/){print"\n"}else{print};$follows_match=/\&/;'\
each.txt file.txt input.txt as.txt arg.txt list.txt isProcessed.txt toSTDOUT.txt

Does what you ask in the in/out example.

The sed script that does the same is (in my opinion) even harder to read:

$ sed '
/\&/ {
N
s/\n\&.*\&$/\
/ 
}' input_file.txt

Now, to me, "delete the line" does not mean "replace the line with a blank line". Which if you take this meaning rather than what's shown in your input and output examples you get a slightly cleaner looking:

$ sed '
/\&/ {
N
s/\n\&.*\&$// 
}' input_file.txt

I hope this is NOT your homework regarding learning sed because you just didn't learn much.