How to extract a value from a string using regex and a shell?

前端 未结 7 1009
Happy的楠姐
Happy的楠姐 2020-12-13 06:11

I am in shell and I have this string: 12 BBQ ,45 rofl, 89 lol

Using the regexp: \\d+ (?=rofl), I want 45 as a result.

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-13 06:41

    It seems that you are asking multiple things. To answer them:

    • Yes, it is ok to extract data from a string using regular expressions, that's what they're there for
    • You get errors, which one and what shell tool do you use?
    • You can extract the numbers by catching them in capturing parentheses:

      .*(\d+) rofl.*
      

      and using $1 to get the string out (.* is for "the rest before and after on the same line)

    With sed as example, the idea becomes this to replace all strings in a file with only the matching number:

    sed -e 's/.*(\d+) rofl.*/$1/g' inputFileName > outputFileName
    

    or:

    echo "12 BBQ ,45 rofl, 89 lol" | sed -e 's/.*(\d+) rofl.*/$1/g'
    

提交回复
热议问题