How can I parse a string using bash to get a number

后端 未结 3 895
轻奢々
轻奢々 2021-01-28 07:51

I have the following string:

PR-1769|7bb12d4152a497cef491e0a1088b3984ad92972f|jaga|

How can I parse the string above using bash so that I get t

3条回答
  •  情歌与酒
    2021-01-28 08:44

    There's no need for grep here: bash has built-in regex support, which is vastly more efficient to use than starting up an external utility just to process a single line:

    re='^PR-([0-9]+)'
    s='PR-1769|7bb12d4152a497cef491e0a1088b3984ad92972f|marvel|'
    
    if [[ $s =~ $re ]]; then
      echo "Matched: ${BASH_REMATCH[1]}"
    fi
    

    You can also use parameter expansions:

    s='PR-1769|7bb12d4152a497cef491e0a1088b3984ad92972f|marvel|'
    s="${s%%'|'*}" # trim off everything after the first |
    s="${s#PR-}"   # trim off the leading PR
    echo "$s"
    

    If you needed to extract the individual fields, by the way, read might be the correct tool for the job:

    s='PR-1769|7bb12d4152a497cef491e0a1088b3984ad92972f|marvel|'
    IFS='|' read -r pr hash username <<<"$s"
    

    ...the above will put PR-1769 into the variable pr, 7bb12d4152a497cef491e0a1088b3984ad92972f into the variable hash, and marvel into the variable username. To strip off the PR-, then, might simply look like:

    echo "${pr#PR-}"
    

    ...or, to print the extracted username:

    echo "$username"
    

    See:

    • BashFAQ #100 ("How do I do string manipulations in bash?")
    • bash-hackers.org parameter expansion reference

提交回复
热议问题