Awk 如果发生匹配,请删除第二个引用
我的数据如下Awk 如果发生匹配,请删除第二个引用,awk,sed,Awk,Sed,我的数据如下 Cell A function (A+B) Cell B function (A^B) function (A+B) function (A1A2) Cell C function (A1A2) function ((B1+B2)A2) 我希望输出为 Cell A function (A+B) Cell B function (A^B) Cell C function (A1A2) 如果函数重复,我只想打印第一个函数行 我试过了 awk "/function/ &a
Cell A
function (A+B)
Cell B
function (A^B)
function (A+B)
function (A1A2)
Cell C
function (A1A2)
function ((B1+B2)A2)
我希望输出为
Cell A
function (A+B)
Cell B
function (A^B)
Cell C
function (A1A2)
如果函数重复,我只想打印第一个函数行
我试过了
awk "/function/ && !a[$0]++{print;next} !/function/{delete a;print}" file
但我的数据没有变化。就像评论中的@Cyrus'一样,我的第一个想法是在
单元格打印记录,然后再打印下一行,但如果您需要它,请另作选择:
$ awk '/function/&&f{print p ORS $0;f=0}{p=$0}/Cell/{f=1}' file
输出:
Cell A
function (A+B)
Cell B
function (A^B)
Cell C
function (A1A2)
解释:
$ awk '
/function/ && f { # seeing "function" when the f flag is up
print p ORS $0 # print stored previous and current records
f=0 # flag down
}
{
p=$0 # store current as previous for next round
}
/Cell/ { # at "Cell"
f=1 # flag up
}' file
(您可以将单元格
存储为f
标志的值,并在设置该值时打印
:
$ awk '/function/&&f{print f ORS $0;f=""}/Cell/{f=$0}'
)这可能适合您(GNU-sed):
通过设置选项-n
打开显式打印
追加下一行
如果第一行开始于单元格
,第二行开始于函数
打印它们
删除第一行并重复
$ awk '/Cell/{c=2} c&&c--' file
Cell A
function (A+B)
Cell B
function (A^B)
Cell C
function (A1A2)
或者,如果“单元格”不总是非功能块中的文本:
$ awk '!/function/{c=2} c&&c--' file
Cell A
function (A+B)
Cell B
function (A^B)
Cell C
function (A1A2)
有关详细信息,请参阅。这个技巧就可以了
$ uniq -w8 file
Cell A
function (A+B)
Cell B
function (A^B)
Cell C
function (A1A2)
比较“function”.length()->8个字符。
uniq
将消除连续的重复条目,因此始终会选择第一个条目
如果您的单元格行没有连续重复,这将是最短的代码。
awk'/Cell/{print;getline;print}文件
?如果您在Windows上运行而使用双引号,则应将该标记添加到问题中。如果这不是原因,那么-不要那样做。在Unix中,始终使用单引号引用字符串(包括脚本),直到您需要双引号来让shell参与解释字符串为止。您应该提到,对于-w
,需要GNU uniq。
$ uniq -w8 file
Cell A
function (A+B)
Cell B
function (A^B)
Cell C
function (A1A2)