Max Wu Max Wu - 4 months ago 12
Bash Question

How can I use sed to delete line with square brackets?

I have one text file.

cat 3.txt
qqq abc cdef (1234) [5689a]
abcfde [aaaa]
ffff [321]


this file with brackets content.

IFS=$'\n'
VAR=( $(</tmp/3.txt) )
LEN=${#VAR[@]}

for (( i = 0; i <LEN; i++ ));do
echo ${VAR[$i]}
sed -i -e "\#${VAR[$i]}#d" /tmp/3.txt
done


I want to echo


qqq abc cdef (1234) [5689a]


then delete this line.
and echo second line. then delete second line.
and echo third line. then delete third line.
but this line with [].How can I use sed to delete this line?

Answer

IMHO, you can't do it with just one sed but below might be an approach

$ cat 38680195
qqq abc cdef (1234) [5689a]
qqq abc cdef (134) [4hgh]
line with <angle brackets>
line without brackets
line with {curly braces}
line with [square brackets]
another line without brackets
$ sed -n '/\[[^]]*\]/p' 38680195 && sed -i.backup '/\[[^]]*\]/d' 38680195
qqq abc cdef (1234) [5689a]
qqq abc cdef (134) [4hgh]
line with [square brackets]
$ cat 38680195
line with <angle brackets>
line without brackets
line with {curly braces}
another line without brackets

Note
A backup of original file is placed in 38680195.backup

$ cat 38680195.backup 
qqq abc cdef (1234) [5689a]
qqq abc cdef (134) [4hgh]
line with <angle brackets>
line without brackets
line with {curly braces}
line with [square brackets]
another line without brackets

Edit

A smarter approach may be

grep '\[[^]]*\]' 38680195 && sed -i.backup '/\[[^]]*\]/d' 38680195

In this case if none of the lines contain [], the sed part wont be executed because it is logically ANDed (See &&).