How can I grep complex strings in variables?

后端 未结 4 1468
情歌与酒
情歌与酒 2021-02-03 22:06

I am trying to grep for a small string in a much larger string. Both strings are being stored as variables and here is a code example:

#!/bin/bash

long_str=$(m         


        
相关标签:
4条回答
  • 2021-02-03 22:31
    if echo "$long_str" | grep -q "$shrt_str";then
      echo "found"
    fi
    

    or

    echo "$long_str" | grep  -q  "$shrt_str"  && echo "found" || echo "not found"
    

    But since you are using bash shell, then use shell internals. No need to call external commands

    shrt_str="guide"
    case "$long_str" in 
       *"$shrt_str"* ) echo "Found";;
       * ) echo "Not found";;
    esac
    
    0 讨论(0)
  • 2021-02-03 22:46

    grep is for files or stdin. If you want to use a variable as stdin then you need to use bash's herestring notation:

    if grep -q "$shrt_str" <<< "$long_str" ; then
    
    0 讨论(0)
  • 2021-02-03 22:46

    You want

    if echo $long_str | grep -q $shrt_str; then
    
    0 讨论(0)
  • 2021-02-03 22:48

    Another Bash-specific technique:

    if [[ $long =~ $short ]]    # regex match
    then
        echo "yes"
    fi
    

    But if you don't need the long string in a variable:

    if man man | grep $short; then ...
    

    but I'm assuming that was just for the purpose of having an example.

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