Grep

From Segfault
Jump to: navigation, search

Let's prepare a file with various character lenghts, so that we can use our grep commands later on:

$ i=1; for c in {a..z}; do perl -e "print \"${c}\"x${i}; print \"\n\""; i=$((i+1)); done
a
bb
ccc
dddd
eeeee
ffffff
ggggggg
hhhhhhhh
iiiiiiiii
jjjjjjjjjj
kkkkkkkkkkk
llllllllllll
mmmmmmmmmmmmm
nnnnnnnnnnnnnn
ooooooooooooooo
pppppppppppppppp
qqqqqqqqqqqqqqqqq
rrrrrrrrrrrrrrrrrr
sssssssssssssssssss
tttttttttttttttttttt
uuuuuuuuuuuuuuuuuuuuu
vvvvvvvvvvvvvvvvvvvvvv
wwwwwwwwwwwwwwwwwwwwwww
xxxxxxxxxxxxxxxxxxxxxxxx
yyyyyyyyyyyyyyyyyyyyyyyyy
zzzzzzzzzzzzzzzzzzzzzzzzzz

Find strings at least 3 characters long:[1]

grep -E '^[[:alpha:]]{3}$' file.txt

Find (and print only) words in a file:[2]

egrep -o '\w+' file.txt

Print last 3 characters[3] of a string:

grep -o '.\{3\}$'

References