Grep multiple strokes on one line (bash)

I need to find multiple hits on the same line (using grep / egrep). In particular, as an example, I need to find all the words surrounding the word "und" in the text "Geschehnis und Beispiel und Grund und Ursachen". But it 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?

+4
source share
2 answers

Not the smartest way, but you can do it awk. The idea is to match the word undand type the word in front of 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 a conclusion like

Geschehnis und Beispiel
Beispiel und Grund
Grund und Ursachen
+2
source

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+)/),
    • print $&
    • s//$1/ (\w+)
+1

Source: https://habr.com/ru/post/1675163/


All Articles