开发者

How to extract the first word that follows a string?

开发者 https://www.devze.com 2023-01-12 14:09 出处:网络
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.

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"?


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'


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]}


You can do:

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

It outputs Geroge


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号