What does grep -Po '…\K…' do? How else can that effect be achieved?

前端 未结 1 991
再見小時候
再見小時候 2021-01-13 10:49

I have this script script.sh:

#!/bin/bash
file_path=$1
result=$(grep -Po \'value=\"\\K.*?(?=\")\' $file_path)
echo $result

and

相关标签:
1条回答
  • 2021-01-13 11:17
    • grep -P enables PCRE syntax. (This is a non-standard extension -- not even all builds of GNU grep support it, as it depends on the optional libpcre library, and whether to link this in is a compile-time option).
    • grep -o emits only matched text, and not the entire line containing said text, in output. (This too is nonstandard, though more widely available than -P).
    • \K is a PCRE extension to regex syntax discarding content prior to that point from being included in match output.

    Since your shell is bash, you have ERE support built in. As an alternative that uses only built-in functionality (no external tools, grep, awk or otherwise):

    #!/usr/bin/env bash
    regex='value="([^"]*)"'                    # store regex (w/ match group) in a variable
    results=( )                             # define an empty array to store results
    while IFS= read -r line; do             # iterate over lines on input
      if [[ $line =~ $regex ]]; then        # ...and, when one matches the regex...
        results+=( "${BASH_REMATCH[1]}" )   # ...put the group's contents in the array
      fi
    done <"$1"                              # with stdin coming from the file named in $1
    printf '%s\n' "${results[*]}"           # combine array results with spaces and print
    

    See http://wiki.bash-hackers.org/syntax/ccmd/conditional_expression for a discussion of =~, and http://wiki.bash-hackers.org/syntax/shellvars#bash_rematch for a discussion of BASH_REMATCH. See BashFAQ #1 for a discussion of reading files line-by-line with a while read loop.

    0 讨论(0)
提交回复
热议问题