从特定字符串中删除括号

4
如果一些文本类似于:

如果一些文本类似于:

cell (ABC)
(A1)
(A2)
function (A1.A2)

我希望获得输出结果

cell ABC
A1
A2
function (A1.A2)

我想从文件的每一行中除了函数行中出现的括号以外,都将括号删除。 使用以下代码:

sed 's/[()]//g' file 

移除每行的括号。我该如何修改上面的代码以获得所需的输出。

2个回答

7
您可以为sed命令添加跳出条件:
sed '/^function /b;s/[()]//g' file

或者,将替换条件限制在不匹配函数上:
sed '/^function /!s/[()]//g' file

2
抱歉,在我发布答案之前没有注意到你的回答。++ - anubhava

6

请尝试以下方法。这些方法使用 GNU awk 编写并测试,其中包含所示的样例。

awk '!/function/{gsub(/[()]/,"")} 1' Input_file

说明:为以上内容添加详细说明。

awk '                ##Starting awk program from here.
!/function/{         ##Checking condition if line does not have function in it then do following.
  gsub(/[()]/,"")    ##Globally substituting ( OR ) with null in current line.
}
1                    ##1 will print current line.
' Input_file         ##Mentioning Input_file name here.

1
gsub(/[()]/,"") 可能更短 - anubhava

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接