Match multiple regular expressions from a single file using awk
Try with:
awk '/foo/||/bar/' Input.txt
awk
regexps are extended regexps while grep
's without -E
are basic regexp. With extended regexp:
awk '/name=|age=|class=|marks=/{nr[NR]; nr[NR+2]}; NR in nr'
Note that standard basic regexp do not have an alternation operator, so
grep 'a\|b'
Will typically not work in every grep
(while a few like GNU grep
support it as an extension).
grep -E 'a|b'
grep -e a -e b
grep 'a
b'
Will work in every grep
though.
Using grep
What if you used the after context switch to grep (-A
) and specified a 1
to get the first line after a match?
$ grep -E -A 1 "name=|age=|class=|marks=" student.txt
Example
Sample file.
$ cat student.txt
name=
1st line after name
2nd line after name
age=
1st line after age
2nd line after age
class=
1st line after class
2nd line after class
marks=
1st line after marks
2nd line after marks
Then when you execute the above command:
$ grep -E -A 1 "name=|age=|class=|marks=" student.txt
name=
1st line after name
--
age=
1st line after age
--
class=
1st line after class
--
marks=
1st line after marks
Using awk
As @RahulPatil suggested using the construct to awk
:
'/string1/||/string2/||...'
Something like this would do what you're looking for.
$ awk '
/name=/||/age=/||/class=/||/marks=/{nr[NR]; nr[NR+1]}; NR in nr
' student.txt
Example
$ awk '
/name=/||/age=/||/class=/||/marks=/{nr[NR]; nr[NR+1]}; NR in nr
' student.txt
name=
1st line after name
age=
1st line after age
class=
1st line after class
marks=
1st line after marks