【问题标题】:trim trailing tabs from a string/column in awk从 awk 中的字符串/列中修剪尾随制表符
【发布时间】:2018-03-14 11:07:07
【问题描述】:

我有一个包含 4 列的文件,由制表符分隔。在最后一列中,引号之间有时可能有尾随制表符。 这是与trim leading and trailing spaces from a string in awk 类似的问题。这是一个例子:

col1 col2 col3 col4
"12" "d" "5" "this is great"
"13" "d" "6" "this is great<tab>"
"14" "d" "7" "this is great<tab><tab>"
"15" "d" "8" "this is great"
"16" "d" "9" "this is great<tab>"

这是我目前想出的:

gawk --re-interval -F '"' 'NF = 9 {if ($8 ~ /\t$/) {gsub(/[\t]+$,"",$8)} ;}'

问题在于它破坏了我的格式,这意味着我没有为每一列添加引号。好消息是列之间的选项卡仍然存在:

col1 col2 col3 col4
12 d 5 this is great
13 d 6 this is great
14 d 7 this is great
15 d 8 this is great
16 d 9 this is great

我做错了什么?

【问题讨论】:

    标签: awk


    【解决方案1】:

    您需要告诉 awk 输出字段分隔符 (OFS) 也是一个引号。例如:

    awk -v OFS='"' -F '"' 'NF == 9 {
      if ($8 ~ /\t$/) {
        gsub(/[\t]+$/,"",$8)
      }
    }
    1' input.txt
    

    输出:

    col1   col2   col3   col4
    "12"   "d"    "5"    "this is great"
    "13"   "d"    "6"    "this is great"
    "14"   "d"    "7"    "this is great"
    "15"   "d"    "8"    "this is great"
    "16"   "d"    "9"    "this is great"
    

    【讨论】:

    • 有没有可能是输出与输入不一致(列间距)?我与 OP 的示例文件进行比较。否则 +1 用于解释问题所在;-)
    • @kvantour: SO 不能正确表示硬标签,所以我们必须适应
    猜你喜欢
    • 2014-01-03
    • 2014-10-30
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 2017-05-24
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多