sábado, 14 de marzo de 2020

[EN] Pills :: using grep and sed

Hello everyone!

Today I bring you a tiny grep pills, a couple of features that I did not know and I think they are very interesting



So let's go there:

Returns # of matches (similar to wc -l)
> grep -c pattern

Shows the line that matches and two lines after
> cat file | grep -A2 pattern

Shows the line that matches and two lines before
> cat file | grep -B2 pattern

Shows the line that matches, two lines before and and two lines after
> cat file | grep -C2 pattern


Extra pill: This reminds me that if you want to add a line to a file, for example, above or below a specific row, you can do it using sed

Imagine that you want to add a line to /etc/passwords file, one above and one below a user named 'esther'

Adds the new line just after the user that starts with 'esther'
> sed ' /^esther/ a newuser:x:1001:1000:New User:/home/user:/bin/sh' /etc/passwd

Adds the new line just before the user that starts with 'esther'
> sed ' /^esther/ i newuser:x:1001:1000:New User:/home/user:/bin/sh' /etc/passwd