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

后端 未结 4 1119
逝去的感伤
逝去的感伤 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: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}'
    

提交回复
热议问题