满足条件时删除字符串

时间:2015-11-12 08:50:52

标签: bash awk sed gawk

我有一个以制表符分隔的文本,在文本中是一个多次出现的字符串,我需要在伴有其他字符串时将其删除。

A       B      C        D   E   F   G   H   I   J
string  string string   car29   ""  ""  ""  ""  ""  string # We don't do anything
string  string string   pool    car29   ""  ""  ""  ""  string # Remove car29
string  string string   fifo    pool    car29   ""  ""  ""  string # Remove car29
string  string string   car29   ""  ""  ""  ""  ""  string # We don't do anything

关键词是car29,我们只是在这个词出现的行上行动

预期产出

A       B      C        D   E   F   G   H   I   J
string  string string   car29   ""  ""  ""  ""  ""  string 
string  string string   pool    ""  ""  ""  ""  ""  string 
string  string string   fifo    pool    ""  ""  ""  ""  string 
string  string string   car29   ""  ""  ""  ""  ""  string 

2 个答案:

答案 0 :(得分:0)

Perl救援!

perl -F'/\t/' -ape 's/(^|(?<=\t))car29($|(?=\t))/""/g if grep $_ ne "car29" && $_ ne q(""), @F[3..8]'
  • -F设置列分隔符
  • -a拆分为colunns(进入@F数组)
  • -p逐行处理输入,打印结果
  • 仅当第3列... 8(只是猜测,您的规范含糊不清)不为空且与car29
  • 不同时,才会进行替换
  • car29位于行首或制表符的开头,然后是行尾或制表符后,替换将""替换为car29。查看断言用于存在多个^ s邻居的情况。可能不需要$car29,因为示例中的前三列和最后一列绝不会包含$(function() { var myDate = new Date(); console.log(myDate.format("yyyy-mm-dd h:MM")); $("#date").html(myDate.format("yyyy-mm-dd h:MM")); });(不完整的规范)。

答案 1 :(得分:0)

使用sed

sed '/\(.*"".*\)\{5\}/! s/car29/""/' <<\eof
A       B      C        D   E   F   G   H   I   J
string  string string   car29   ""  ""  ""  ""  ""  string # We don't do anything
string  string string   pool    car29   ""  ""  ""  ""  string # Remove car29
string  string string   fifo    pool    car29   ""  ""  ""  string # Remove car29
string  string string   car29   ""  ""  ""  ""  ""  string # We don't do anything
eof

A       B      C        D   E   F   G   H   I   J
string  string string   car29   ""  ""  ""  ""  ""  string # We don't do anything
string  string string   pool    ""   ""  ""  ""  ""  string # Remove car29
string  string string   fifo    pool    ""   ""  ""  ""  string # Remove car29
string  string string   car29   ""  ""  ""  ""  ""  string # We don't do anything