我是linux新手。我有tab delim文本文件,如下面的
A1 title body.1 gene
A1 head head.1 head
A1 trunk trunk.1 trunk
A1 tail tail.1 tail
A2 title body.2 gene
A2 head head.2 head
A2 trunk trunk.2 trunk
A2 tail tail.2 tail
A3 title body.3 gene
A3 head head.3 head
A3 trunk trunk.3 trunk
A4 title title.4 gene
A4 trunk trunk.4 trunk
A4 tail tail.4 tail
我想在包含单词" gene"的每一行之前引入一个新行。在最后一栏中如下:
A1 title body.1 gene
A1 head head.1 head
A1 trunk trunk.1 trunk
A1 tail tail.1 tail
A2 title body.2 gene
A2 head head.2 head
A2 trunk trunk.2 trunk
A2 tail tail.2 tail
A3 title body.3 gene
A3 head head.3 head
A3 trunk trunk.3 trunk
A4 title title.4 gene
A4 trunk trunk.4 trunk
A4 tail tail.4 tail
我尝试了以下命令
sed 's/gene/\
\n&\g' file.txt
但它在包含word" gene"。
的行后面引入了一个新行如果任何人可以指导我如何在包含单词" gene
"的非常行之前引入新行,那将会很棒。在最后一栏。
答案 0 :(得分:1)
使用反向引用
sed 's/\(^.*gene\)/\n\1/g' file.txt
答案 1 :(得分:1)
只需检查最后一个字段是否为gene
。如果是这样,请打印一个空行:
awk '$NF=="gene" {print ""}1' file
返回:
$ awk '$NF=="gene" {print ""}1' file
A1 title body.1 gene
A1 head head.1 head
A1 trunk trunk.1 trunk
A1 tail tail.1 tail
A2 title body.2 gene
A2 head head.2 head
A2 trunk trunk.2 trunk
A2 tail tail.2 tail
A3 title body.3 gene
A3 head head.3 head
A3 trunk trunk.3 trunk
A4 title title.4 gene
A4 trunk trunk.4 trunk
A4 tail tail.4 tail
答案 2 :(得分:1)
你可能想要这样的东西(扩展的正则表达式语法):
$ sed -r 's/(^.*?\tgene$)/\n\1/' example
A1 title body.1 gene
A1 head head.1 head
A1 trunk trunk.1 trunk
A1 tail tail.1 tail
A2 title body.2 gene
A2 head head.2 head
A2 trunk trunk.2 trunk
A2 tail tail.2 tail
A3 title body.3 gene
A3 head head.3 head
A3 trunk trunk.3 trunk
A4 title title.4 gene
A4 trunk trunk.4 trunk
A4 tail tail.4 tail
在这个正则表达式中你可以看到:
's/.../.../'
(^.*?\tgene$)
。 \n\1
请注意您的问题中有一个问题:
我想在每行包含单词之前引入一个新行 最后一栏中的“基因”
这导致假设您需要将结果的第一行显示为空(或者确切地说是单个换行符)
但是,您的示例的第一行显然没有空行。 如果这真的是你需要的,你应该使用sed寻址:
pono@pono-carbon:~$ sed -r '2,$s/(^.*?\tgene$)/\n\1/' example
A1 title body.1 gene
A1 head head.1 head
A1 trunk trunk.1 trunk
A1 tail tail.1 tail
A2 title body.2 gene
A2 head head.2 head
A2 trunk trunk.2 trunk
A2 tail tail.2 tail
A3 title body.3 gene
A3 head head.3 head
A3 trunk trunk.3 trunk
A4 title title.4 gene
A4 trunk trunk.4 trunk
A4 tail tail.4 tail
答案 3 :(得分:0)
使用sed可以使用insert命令i:
sed '2,${/[\t ]gene$/i\
;}' file
2,$
条件用于防止在开头添加前导换行符。