linux - 使用 Sed 按列替换字符串

标签 linux unix sed replace

鉴于此数据

34 foo
34 bar
34 qux
62 foo1
62 qux
78 qux 

如果它是“qux”,我想将第 2 列的字符串替换为“”。 结果:

34 foo
34 bar
34 
62 foo1
62 
78  

如何使用 sed 做到这一点?特别是数据非常大,有 ~10^7 行

最佳答案

不会实际上用 sed 来做,因为那不是完成这项工作的最佳工具。每当有人提到列时,awk 工具就是我的首选工具。

cat file | awk '$2 == "qux" { print $1 } $2 != "qux" { print $0 }'

或最简单的形式:

cat file | awk '{ if ($2 == "qux") {$2 = ""}; print }'

如果必须使用sed:

cat file | sed 's/  *qux *$//'

确保您使用正确的空格(以上仅使用空格)。

关于linux - 使用 Sed 按列替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/708081/

相关文章:

linux - 如何为我的 shell 脚本制作手册页?

linux - 如何使用 awk 只替换第二个实例一次

regex - 更改第一个括号中后跟第三个/方括号的文本

linux - 在 unix 中执行 "jobs"命令时,+ 和 - 符号表示什么?

linux - AwesomeWM 时间不更新?

regex - 查找给定字符串后的第一个字符

linux - 关于 sed 模式匹配的建议

PHP配置错误DBA : Could not find necessary header file(s)

python - cloudera 5 python API无法创建集群

linux - shell : How to get pid given apart of its name string