【问题标题】:Extract string between qoutes in a script提取脚本中引号之间的字符串
【发布时间】:2020-03-18 17:14:08
【问题描述】:

我的文字-

(
    "en-US"
)

我需要什么-

en-US

目前我可以通过管道得到它

... | tr -d '[:space:]' | sed s/'("'// | sed s/'("'// | sed s/'")'//

我想知道是否有一种简单的方法来提取 qoutes 之间的字符串,而不是一个一个地切掉无用的部分

【问题讨论】:

    标签: bash shell sed scripting grep


    【解决方案1】:

    请您尝试以下操作。其中var 是 bash 变量,其中显示了存储在其中的示例值。

    echo "$var" | awk 'match($0,/".*"/){print substr($0,RSTART+1,RLENGTH-2)}'
    

    说明:以下仅作说明之用。

    echo "$var" |                              ##Using echo to print variable named var and using |(pipe) to send its output to awk command as an Input.
    awk '                                      ##Starting awk program from here.
    match($0,/".*"/){                        ##using match function of awk to match a regex which is to match from  till next occurrence of "  by this match 2 default variables named RSTART and RLENGTH will be set as per values.
      print substr($0,RSTART+1,RLENGTH-2)      ##Where RSTART means starting point index of matched regex and RLENGTH means matched regex length, here printing sub-string whose starting point is RSTART and ending point of RLENGTH to get only values between " as per request.
    }'                                         ##Closing awk command here.
    

    【讨论】:

    • @R347,当然添加了详细的解释,如果有任何疑问,请让我知道,干杯。
    • @EdMorton,好的先生,谢谢你告诉我我现在改变了,干杯。
    【解决方案2】:

    ... | grep -oP '(?<=").*(?=")'

    解释:

    • -o: 只输出匹配字符串
    • -P: 使用 Perl 风格的正则表达式
    • (?<="):向后看,所以只匹配前面有双引号的文本
    • .*:匹配任意字符
    • (?="):前瞻,所以只匹配后跟双引号的文本

    【讨论】:

      【解决方案3】:

      sed

      echo '(
          "en-US"
      )' | sed -rn 's/.*"(.*)".*/\1/p'
      

      使用 2 个命令

      echo '(
          "en-US"
      )' | tr -d "\n" | cut -d '"' -f2
      

      【讨论】:

        【解决方案4】:

        考虑使用

        ... | grep -o '"[^"]\{1,\}"' | sed -e 's/^"//' -e 's/"$//' 
        

        grep会提取引号之间的所有子串(不包括空的),后面的sed会去掉两端的引号。

        【讨论】:

          【解决方案5】:

          还有这个?

          ... | grep '"' | cut -d '"' -f 2

          如果您仅按行引用 1 个值,则此方法有效。

          【讨论】:

            猜你喜欢
            • 2011-01-05
            • 1970-01-01
            • 2023-03-06
            • 1970-01-01
            • 1970-01-01
            • 2012-09-05
            • 1970-01-01
            • 2017-11-10
            相关资源
            最近更新 更多