extracting a string between two quotes in bash

前端 未结 3 730
被撕碎了的回忆
被撕碎了的回忆 2021-01-19 07:00

I have example string like Test \"checkin_resumestorevisit - Online_V2.mt\" Run

and i want to extract the text between the two quotes in bash. I tried

相关标签:
3条回答
  • 2021-01-19 07:30

    If you want to extract content between the first " and the last ":

    s='Test "checkin_resumestorevisit - Online_V2.mt" Run'
    s=${s#*'"'}; s=${s%'"'*}
    echo "$s"
    
    0 讨论(0)
  • 2021-01-19 07:50

    In order to extract the substring between quotes you can use one of these alternatives:

    Alternative 1:

    SUBSTRING=`echo "$SUBSTRING" | cut -d'"' -f 2`
    

    Alternative 2:

    SUBSTRING=`echo "$SUBSTRING" | awk -F'"' '{print $2}'`
    

    Alternative 3:

    set -f;IFS='"'; SUBSTRING=($SUBSTRING); SUBSTRING=${SUBSTRING[1]};set +f
    
    0 讨论(0)
  • 2021-01-19 07:53

    Other weird ideas to not let @arton-dorneles alone :^)

    But my favourite is @charles-duffy answer.

    [[ "$SUBSTRING" =~ \"(.*)\" ]] && SUBSTRING="${BASH_REMATCH[1]}"
    
    IFS=\" read -r _ SUBSTRING _ <<<"$SUBSTRING"
    
    # bonus, match either ' or " by pair
    SUBSTRING=$(echo "$SUBSTRING" | sed -r "s/.*?([\"'])(.*)\1.*/\2/")
    

    Note that bash create a temporary file for "here string" (<<<) as it does for here documents.

    Edit

    It took me way too long to fully understand Charles Duffy critics; for readers, this could be when:

    SUBSTRING='*"inside text" outside text'
    

    In this scenario, the following would be unsafe because the star would be expanded, listing files and moving the desired result index:

    IFS=\" eval '_=($SUBSTRING);SUBSTRING="${_[1]}"'
    
    IFS=\" read -ra _ <<<"$SUBSTRING";SUBSTRING=${_[1]}
    
    0 讨论(0)
提交回复
热议问题