如何使用sed删除带有方括号的行? [英] How can I use sed to delete line with square brackets?

查看:109
本文介绍了如何使用sed删除带有方括号的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只有一个文本文件.

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

此文件带有括号内容.

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

我想回声

qqq abc cdef(1234)[5689a]

qqq abc cdef (1234) [5689a]

然后删除此行.并回显第二行.然后删除第二行.并回显第三行.然后删除第三行.但此行带有[].如何使用sed删除此行?

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?

推荐答案

恕我直言,您不能仅用一个 sed 来做到这一点,但下面可能是一种方法

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

注意
原始文件的备份位于38680195.backup

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

修改

更聪明的方法可能是

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

在这种情况下,如果所有行都不包含 [] ,则sed部分将不会执行,因为它是在逻辑上进行 AND 的操作(请参见&&).

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

这篇关于如何使用sed删除带有方括号的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆