首页 > 解决方案 > 删除文本文件第二列中的字符串和空格

问题描述

我想从TAB-DELIMITED文本文件的第二列中删除特定的字符串“num=” 。

this is a sentence  num= 123.45
this is a phrase    num= 768.90

我知道如何使用 sed 删除“num=”,但我似乎无法删除“=”之后的空格。我想要的是这样的:

this is a sentence  123.45
this is a phrase    768.90

此外,如果第二列编号大于 500,我想标记第三列中的行,如下所示:

this is a sentence  123.45  true
this is a phrase    768.90  false

我尝试了什么:

我使用 awk 将第二列放入它自己的文件中,然后:

sed -e s/num=//g -i            # Removes just "num="
sed -e s/num= //g -i           # I get an error 
sed -e s/num=\s//g -i          # No effect

标签: linuxbashawksed

解决方案


使用 awk:

$ awk '
BEGIN { FS=OFS="\t" }                  # set delimiters to tab
{ 
    sub(/num= /,"",$2)                 # remove num= 
    print $0,($2+0>500?"true":"false") # output edited record and true/false
}' file
this is a sentence  123.45  false
this is a phrase    768.90  true

推荐阅读