I need to find multiple hits in one line (using grep/egrep). Specifically, as an example, I need to find all words surrounding the word "und" in the text "Geschehnis und Beispiel und Grund und Ursachen". But egrep "\\w+ und \\w+"
has only two, not three hits:
$ echo "Geschehnis und Beispiel und Grund und Ursachen" | egrep -o "\w+ und \w+"
> Geschehnis und Beispiel
> Grund und Ursachen
I also need to find "Beispiel und Grund". How can I do this?
Not the most intelligent of ways, but can be done in awk
. The idea is to match the word und
and print the word before it and next to it.
echo "Geschehnis und Beispiel und Grund und Ursachen" | awk '{for(i=1;i<=NF;i++) { if (match($i,/^und$/)) { print prev,$i,$(i+1) }; prev=$i }}'
which produces an output as
Geschehnis und Beispiel
Beispiel und Grund
Grund und Ursachen
With perl
$ s='Geschehnis und Beispiel und Grund und Ursachen'
$ # can also use: perl -pe 's/(\w+ und )(?=(\w+) )/$1$2\n/g'
$ echo "$s" | perl -lne 'while(/\w+ und (\w+)/){print $&; s//$1/}'
Geschehnis und Beispiel
Beispiel und Grund
Grund und Ursachen
while(/\\w+ und (\\w+)/)
as long as input line matches this regex
print $&
print the whole matched string s//$1/
replace the matched string with only the captured group (\\w+)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.