Return a regex match in a Bash script, instead of replacing it

前端 未结 9 759
面向向阳花
面向向阳花 2021-01-31 04:30

I just want to match some text in a Bash script. I\'ve tried using sed but I can\'t seem to make it just output the match instead of replacing it with something.



        
相关标签:
9条回答
  • 2021-01-31 04:34

    using just the bash shell

    declare -a array
    i=0
    while read -r line
    do
            case "$line" in
                *TestT*String* )
                while true
                do
                    line=${line#*TestT}
                    array[$i]=${line%%String*}
                    line=${line#*String*}
                    i=$((i+1))
                    case "$line" in
                        *TestT*String* ) continue;;
                        *) break;;
                    esac
                done
                esac
    done <"file"
    echo ${array[@]}
    
    0 讨论(0)
  • 2021-01-31 04:36

    Use grep. Sed is an editor. If you only want to match a regexp, grep is more than sufficient.

    0 讨论(0)
  • 2021-01-31 04:44

    Pure Bash. Use parameter substitution (no external processes and pipes):

    string="TestT100String"
    
    echo ${string//[^[:digit:]]/}
    

    Removes all non-digits.

    0 讨论(0)
  • 2021-01-31 04:46

    Well , the Sed with the s/"pattern1"/"pattern2"/g just replaces globally all the pattern1s to pattern 2.

    Besides that, sed while by default print the entire line by default . I suggest piping the instruction to a cut command and trying to extract the numbers u want :

    If u are lookin only to use sed then use TRE:

    sed -n 's/.*\(0-9\)\(0-9\)\(0-9\).*/\1,\2,\3/g'.
    

    I dint try and execute the above command so just make sure the syntax is right. Hope this helped.

    0 讨论(0)
  • 2021-01-31 04:53

    You could do this purely in bash using the double square bracket [[ ]] test operator, which stores results in an array called BASH_REMATCH:

    [[ "TestT100String" =~ ([0-9]+) ]] && echo "${BASH_REMATCH[1]}"
    
    0 讨论(0)
  • 2021-01-31 04:54

    I don't know why nobody ever uses expr: it's portable and easy.

    newName()
    {
     #Get input from function
     newNameTXT="$1"
    
     if num=`expr "$newNameTXT" : '[^0-9]*\([0-9]\+\)'`; then
      echo "contains $num"
     fi
    }
    
    0 讨论(0)
提交回复
热议问题