extracting a string between two quotes in bash

前端 未结 3 729
被撕碎了的回忆
被撕碎了的回忆 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: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]}
    

提交回复
热议问题