使用 grep/sed/perl 在单行中提取多个项目
extract multiple items on single line using grep/sed/perl
我有一个像这样的大文本文件:
=?accession=P12345;=?position=999;
=?accession=Q19283;=?position=777;
=?accession=A918282;=?position=888;
我想提取 accession=
和 ;
之间的术语,然后还提取 position=
和 ;
之间的术语
所以我得到:
P12345 999
Q19283 777
A918282 888
我需要在它们之间进行 grep 处理的字符串变得更加复杂,所以我设想了一个硬编码解决方案。
我知道我可以采用 "grep between two strings" 方法:
grep -Po 'accession= \K.*(?= ;)'
但我不知道如何从输入的同一行中提取后续内容,使其也出现在与输出相同的行中。
我真的不介意这是如何完成的,只要我可以从 linux 命令行调用它即可。
谢谢。
这个 awk
应该有效:
awk -F ';' '{gsub(/=[^=]*=/, ""); =} 1' file
P12345 999
Q19283 777
A918282 888
sed -r 's/.*accession=([^;]*);.*position=([^;]*).*/ /' textfile
这个perl单行
perl -wnE'say join " ", /(?:accession|position)=([^;]+)/g' input.txt
打印所需的输出。
您可以像这样更新 grep 表达式。
grep -oP "(accession=\K\w+)|(position=\K\d+)" file
输出:
P12345
999
Q19283
777
A918282
888
如需格式化,请使用 paste
:
grep -oP "(accession=\K\w+)|(position=\K\d+)" file | paste -d ' ' - -
输出:
P12345 999
Q19283 777
A918282 888
另一个简单的 awk 解决方案:
awk -F"=|;" '{print , }' file
输出:
P12345 999
Q19283 777
A918282 888
我有一个像这样的大文本文件:
=?accession=P12345;=?position=999;
=?accession=Q19283;=?position=777;
=?accession=A918282;=?position=888;
我想提取 accession=
和 ;
之间的术语,然后还提取 position=
和 ;
所以我得到:
P12345 999
Q19283 777
A918282 888
我需要在它们之间进行 grep 处理的字符串变得更加复杂,所以我设想了一个硬编码解决方案。
我知道我可以采用 "grep between two strings" 方法:
grep -Po 'accession= \K.*(?= ;)'
但我不知道如何从输入的同一行中提取后续内容,使其也出现在与输出相同的行中。
我真的不介意这是如何完成的,只要我可以从 linux 命令行调用它即可。
谢谢。
这个 awk
应该有效:
awk -F ';' '{gsub(/=[^=]*=/, ""); =} 1' file
P12345 999
Q19283 777
A918282 888
sed -r 's/.*accession=([^;]*);.*position=([^;]*).*/ /' textfile
这个perl单行
perl -wnE'say join " ", /(?:accession|position)=([^;]+)/g' input.txt
打印所需的输出。
您可以像这样更新 grep 表达式。
grep -oP "(accession=\K\w+)|(position=\K\d+)" file
输出:
P12345 999 Q19283 777 A918282 888
如需格式化,请使用
paste
:grep -oP "(accession=\K\w+)|(position=\K\d+)" file | paste -d ' ' - -
输出:
P12345 999 Q19283 777 A918282 888
另一个简单的 awk 解决方案:
awk -F"=|;" '{print , }' file
输出:
P12345 999 Q19283 777 A918282 888