python - 如果列检查为特定值,则提取行 - Unix

标签 python awk sed

鉴于我有一个以制表符分隔的文件,其中第一列作为某种索引:

$ 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 脚本?

最佳答案

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

首先是一些测试 Material :

$ 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

关于python - 如果列检查为特定值,则提取行 - Unix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40988313/

相关文章:

bash - 使用 sed 转义字符串变量中的符号

regex - 在 sed 或 awk 中的两个匹配项之间的最后一行之前插入文本

python - Matplotlib:刻度标签与字体设置不一致(LaTeX 文本示例)

linux - #awk If else 循环在 ksh 中不起作用

bash - 使用 awk 计算两列的差异

awk - 如何将此命令放在Makefile中?

python - 类型错误 : string indices must be integers - while trying to read secret

python - 在 Python 中记录为调用者模块

python - 在 Python Qt 的组合框中逐行嵌入文件

linux - 如何使用 sed 将数据文件中的十进制指数值替换为 0