Position of a string within a string using Linux shell script?

后端 未结 4 1109
逝去的感伤
逝去的感伤 2020-12-05 06:35

If I have the text in a shell variable, say $a:

a=\"The cat sat on the mat\"

How can I search for \"cat\" and return 4 using a

相关标签:
4条回答
  • 2020-12-05 07:00

    I used awk for this

    a="The cat sat on the mat"
    test="cat"
    awk -v a="$a" -v b="$test" 'BEGIN{print index(a,b)}'
    
    0 讨论(0)
  • 2020-12-05 07:02

    You can use grep to get the byte-offset of the matching part of a string:

    echo $str | grep -b -o str
    

    As per your example:

    [user@host ~]$ echo "The cat sat on the mat" | grep -b -o cat
    4:cat
    

    you can pipe that to awk if you just want the first part

    echo $str | grep -b -o str | awk 'BEGIN {FS=":"}{print $1}'
    
    0 讨论(0)
  • 2020-12-05 07:12
    echo $a | grep -bo cat | sed 's/:.*$//'
    
    0 讨论(0)
  • 2020-12-05 07:14

    With bash

    a="The cat sat on the mat"
    b=cat
    strindex() { 
      x="${1%%$2*}"
      [[ "$x" = "$1" ]] && echo -1 || echo "${#x}"
    }
    strindex "$a" "$b"   # prints 4
    strindex "$a" foo    # prints -1
    
    0 讨论(0)
提交回复
热议问题