Linux Tips and Tricks

Linux Tips and Tricks

Awk and Grep

December29

Awk and Grep

we are going to see how the grep and awk works for the same functionality

1
2
3
4
5
6
7
8
9
10
11
$ cat test.txt
one
two
three
four
five
six
seven
eight
nine
ten

1) Grep the pattern using grep and awk

1
2
3
4
5
6
7
8
9
$ grep "o" test.txt
one
two
four
 
$ awk '/o/' test.txt
one
two
four

2) Print the pattern line number using grep and awk

1
2
3
4
5
6
7
8
9
$ grep -n "o" test.txt
1:one
2:two
4:four
 
$ awk '/o/ {print NR":"$0}' test.txt
1:one
2:two
4:four

3) Print the number of occurences of in a file using grep and awk

1
2
3
4
5
$ grep -c "o" test.txt
3
 
$ awk '/o/ {i++}END{print i}' test.txt
3

4) Invert the sense of matching, to select non-matching lines using grep and awk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$ grep -v "o" test.txt
three
five
six
seven
eight
nine
ten
 
$ awk '!/o/' test.txt
three
five
six
seven
eight
nine
ten

5) Print the filename if pattern found in the file.

1
2
3
4
5
6
7
8
9
10
11
$ grep -l "one" *
armstrong
armstrong1
test.pl
test.txt
 
$ awk '$0~/one/{a[FILENAME]=1}END{for(i in a)print i}' *
armstrong1
test.pl
test.txt
armstrong

6) grep multiple patterns using grep and awk

1
2
3
4
5
6
7
$ grep -E "one|two" test.txt
one
two
 
$ awk '/one/ || /two/' test.txt
one
two
posted under Uncategorized

Email will not be published

Website example

Your Comment:


Recent Comments

    Categories