【问题标题】:remove quotes from specific field - integer between quotes从特定字段中删除引号 - 引号之间的整数
【发布时间】:2015-06-14 10:55:52
【问题描述】:

我想从引号之间有整数的特定字段中删除引号。

从此行:"AAA","99"

到这一行:"AAA",99

【问题讨论】:

    标签: regex linux awk sed


    【解决方案1】:

    使用sed

    s='"AAA","99"'
    sed 's/"\([0-9]*\)"/\1/g' <<< "$s"
    "AAA",99
    

    【讨论】:

      【解决方案2】:

      用 GNU sed 试试这个:

      echo '"AAA","99"' | sed -E 's/"([0-9]+)"$/\1/'
      

      输出:

      “AAA”,99

      【讨论】:

        【解决方案3】:

        使用 awk:

        awk -F , 'BEGIN { OFS = FS } $2 ~ /^"[0-9]+"$/ { gsub(/"/, "", $2) } 1'
        

        工作原理如下:

        BEGIN { OFS = FS }  # Delimit output the same way as the input
        
        $2 ~ /^"[0-9]+"$/ { # if the second field ($2) consists of only numbers encased
                            # by double quotes (i.e., matches the regex ^"[0-9]"$)
          gsub(/"/, "", $2) # remove the quotes from it
        }
        1                   # print in any case
        

        要使其适用于任何(而不仅仅是特定字段),请在循环中进行替换:

        awk -F , 'BEGIN { OFS = FS } { for(i = 1; i <= NF; ++i) if($i ~ /^"[0-9]+"$/) { gsub(/"/, "", $i) } } 1'
        

        这里的改动是

        {                              # Do this unconditionally in every line:
          for(i = 1; i <= NF; ++i) {   # wade through all the fields
            if($i ~ /^"[0-9]+"$/) {    # then do with them the same thing as before.
              gsub(/"/, "", $i)
            }
          }
        }
        

        【讨论】:

        • 嗨,如果我希望对引号之间有整数的每一列都执行此操作,该怎么办?不只是秒列
        • 韦德穿过田野,为所有人做改造。查看编辑。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-30
        • 2018-05-30
        • 2016-08-05
        • 2014-11-19
        • 2021-04-10
        • 1970-01-01
        相关资源
        最近更新 更多