如果列签出为特定值,则提取行

2024-09-22 16:38:14 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个以制表符分隔的文件,第一列作为某种索引:

$ echo -e "0\tabc\txyz\n1\twhatever ever\tfoobar\n0\t12f2\t1" > test.txt
$ cat test.txt 
0   abc xyz
1   whatever ever   foobar
0   12f2    1

我想提取第一列中索引具体为0或1的行。你知道吗

我可以在Python中执行此操作:

$ python -c "print '\n'.join([line.strip() for line in open('test.txt') if line.split('\t')[0] == '0'])"

0   abc xyz
0   12f2    1

但是sed/awk(或任何unix工具)与短python脚本的等价物是什么?


Tags: 文件testechotxtline制表符abcxyz
3条回答

如果要查找第一列为0或1的记录:

首先是一些测试材料:

$ cat file
0 yes sir
1 yes sir
10 nope
01 nope
00 nope

在awk中:

$ awk '$1 == "1" || $1 == "0"' file
0 yes sir
1 yes sir

这些将失败:

$ awk '$1 == 0' file
0 yes sir
00 nope
$ awk '$1 == 1' file
1 yes sir
01 nope

使用sed:

sed '/^0\t/!d' test.txt

这里的所有其他答案都使用regex,并且还存在匹配“01”、“11”、“12”等的问题。使用awk,可以测试字符串的相等性:

awk '$1 == 0' test.txt
awk '$1 == 1' test.txt
awk '$1 <= 1' test.txt

相关问题 更多 >