How to extract the first word that follows a strin

2019-09-02 10:56发布

For example, say I have a text file example.txt that reads: I like dogs. My favorite dog is George because he is my dog. George is a nice dog.

Now how do I extract "George" given that it is the first word that follows "My favorite dog is"?

What if there as more than one space, e.g. My favorite dog is George .....

Is there a way to reliably extract the word "George" regardless of the number of spaces between "My favorite dog is" and "George"?

4条回答
smile是对你的礼貌
2楼-- · 2019-09-02 11:20

Pure Bash:

string='blah blah ! HEAT OF FORMATION 105.14088 93.45997 46.89387 blah blah'
pattern='HEAT OF FORMATION ([^[:blank:]]*)'
[[ $string =~ $pattern ]]
match=${BASH_REMATCH[1]}
查看更多
姐就是有狂的资本
3楼-- · 2019-09-02 11:23

If you do not have perl installed you can use sed:

cat example.txt | sed 's/my favourite dog is *\([a-zA-Z]*\) .*/\1/g'
查看更多
劫难
4楼-- · 2019-09-02 11:30

If you are trying to search a file, especially if you have a big file, using external tools like sed/awk/perl are faster than using pure bash loops and bash string manipulation.

sed 's/.*HEAT OF FOMATION[ \t]*\(.[^ \t]*\).*/\1/'  file

Pure bash string manipulation are only good when you are processing a few simple strings inside your script. Like manipulating a variable.

查看更多
Explosion°爆炸
5楼-- · 2019-09-02 11:42

You can do:

cat example.txt | perl -pe 's/My favorite dog is\s+(\w+).*/\1/g'

It outputs Geroge

查看更多
登录 后发表回答