Awk grep:在特定列中保留具有特定字符串的行
我试图挑出在特定列中具有特定值的行,并将其保存到输出中。我正试着和格雷普一起做这件事。可能吗 我的数据如下所示:Awk grep:在特定列中保留具有特定字符串的行,awk,sed,grep,Awk,Sed,Grep,我试图挑出在特定列中具有特定值的行,并将其保存到输出中。我正试着和格雷普一起做这件事。可能吗 我的数据如下所示: apple 5 abcdefd ewdsf peach 5 ewtdsfe wtesdf melon 1 ewtedf wersdf orange 3 qqqwetr hredfg 我想挑出第二列值为5的行,并将其保存到新的outputfile apple 5 abcdefd ewdsf peach 5 ewtdsfe w
apple 5 abcdefd ewdsf
peach 5 ewtdsfe wtesdf
melon 1 ewtedf wersdf
orange 3 qqqwetr hredfg
我想挑出第二列值为5的行,并将其保存到新的outputfile
apple 5 abcdefd ewdsf
peach 5 ewtdsfe wtesdf
我会感谢你的帮助 简单的方法是:
grep '5' MyDataFile
结果是:
apple 5 abcdefd ewdsf
peach 5 ewtdsfe wtesdf
要将其捕获到新文件中,请执行以下操作:
grep '5' MyDataFile > newfile
注意:这将在MyDataFile中的任何位置找到一个5。仅限于第二列,一个简短的脚本将适合您的需要。如果只想将其限制在第二列,则可以使用如下快速脚本。用法:脚本编号数据文件
:
#!/bin/bash
while read -r fruit num stuff || [ -n "$stuff" ]; do
[ "$num" -eq "$1" ] && printf "%s %s %s\n" "$fruit" "$num" "$stuff"
done <"$2"
尝试一下:
grep '^[^\s]\+\s5.*$' file.txt
模式查找行首,后跟多个非空格字符,后跟空格,后跟5,后跟任意数量的字符,然后是eol。要在第二个字段为
5
时打印,请使用:awk'$2==5'文件
使用grep
可能是可行的,但执行此操作的适当工具肯定是awk
。您可以过滤第二列上有5行的每一行
awk '$2 == 5'
解释
awk
将其输入拆分为记录(通常是一行)和字段(通常是一列),并对符合特定条件的记录执行操作。这里
awk '$2 == 5'
是的缩写形式
awk '$2 == 5 {print($0)}'
也就是说
For each record, if the second field ($2) is 5, print the full record ($0).
变化
如果需要动态选择用于筛选值的键值,请使用awk
的-v
选项:
awk -v "key=5" '$2 == key {print($0)}'
如果需要保留文件的第一行,因为它包含表的标题,请使用跟踪当前记录序号的NR
变量:
awk 'NR == 1 || $2 == 5'
字段分隔符是定义哪些文本分隔列的正则表达式,可以使用-F
字段对其进行修改。例如,如果您的数据位于基本CSV文件中,则过滤器将为
awk -F", *" '$2 == 5'
访问tag wiki查找一些有用的信息,以便开始学习
awk
您可以获得以下命令
$ cat data.txt
apple 5 abcdefd ewdsf
peach 5 ewtdsfe wtesdf
melon 1 ewtedf wersdf
orange 3 qqqwetr hredfg
grape 55 kkkkkkk aaaaaa
$ grep -E '[^ ]+ +5 .*' data.txt > output.txt
$ cat output.txt
apple 5 abcdefd ewdsf
peach 5 ewtdsfe wtesdf
只有使用grep
命令才能得到答案。
但我强烈建议您使用
awk
命令。我希望将其限制在第二列。对不起,我贴的例子不好。其他列中有数值。*$
部分没有用。你永远不会想到西班牙宗教法庭!☺若输入表有一个标题行,我们如何保存它?
$ cat data.txt
apple 5 abcdefd ewdsf
peach 5 ewtdsfe wtesdf
melon 1 ewtedf wersdf
orange 3 qqqwetr hredfg
grape 55 kkkkkkk aaaaaa
$ grep -E '[^ ]+ +5 .*' data.txt > output.txt
$ cat output.txt
apple 5 abcdefd ewdsf
peach 5 ewtdsfe wtesdf