Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete line in file matching one string but not matching another - SED, BASH?

Tags:

linux

bash

unix

sh

sed

I want to remove all lines in a file which contain the word "test" but if that line contains "test@" then I do not want to delete it.

There is probably some funky way of doing this with sed but I am struggling, I tried to write a bash loop using sed but this is probably stupid.

filetest=/tmp/filetest
filetest_tmp=/tmp/filetest.tmp<
line_num=0

while read line; do
        line_num=$(($line_num+1))
        if [[ $line == *rootsh* ]] && [[ $line != *root@* ]]
                then
                sed -e "${line_num}"'d' $filetest >> $filetest_tmp
        fi
done < $filetest
cp $syslog_tmp $filetest

As you can tell, I'm a newb at this :(

like image 870
WonderOatmeal Avatar asked Jun 30 '11 06:06

WonderOatmeal


1 Answers

sed -e '/test/{/test@/!d;}'

The first pattern matches the lines containing 'test'; the second pattern deletes lines unless they match 'test@'.

Tested on the data file:

aaaa
bbbtestbbb
ccctest@ccc
test!
dddd

Output:

aaaa
ccctest@ccc
dddd

That seems to meet your requirements.

like image 188
Jonathan Leffler Avatar answered Sep 30 '22 14:09

Jonathan Leffler