Article 4VJV3 Fun with grep for newbies

Fun with grep for newbies

by
teckk
from LinuxQuestions.org on (#4VJV3)
Fun with grep for newer members.

Lets start with this list of items to use.
Code:list="
[12.1]
cat
horse
MOUSE
Cow
[12.3]
house
[49.1]
[49.2]
chair
[55.1]
dog
car
26
28
132
aardvark
"grep examples:
Code:#just the numeric items between []
grep -oP '(?<=\[).*(?=\])' <<< "$list"
12.1
12.3
49.1
49.2
55.1

grep -oP '\[\K[^]]+' <<< "$list"
12.1
12.3
49.1
49.2
55.1

#keep the brackets
grep -o '\[.*\]' <<< "$list"
[12.1]
[12.3]
[49.1]
[49.2]
[55.1]

grep '[0-9][0-9].[0-9]' <<< "$list"
[12.1]
[12.3]
[49.1]
[49.2]
[55.1]

#items that have 3 digits
grep '[0-9][0-9][0-9]' <<< "$list"
132

grep '[0-9]\{3\}' <<< "$list"
132

#one or more digits
grep '[0-9]\{1,\}' <<< "$list"
[12.1]
[12.3]
[49.1]
[49.2]
[55.1]
26
28
132

#start with digit
grep '^[0-9]' <<< "$list"
26
28
132

#do not start with digit
grep '[^0-9]' <<< "$list"
[12.1]
cat
horse
MOUSE
Cow
[12.3]
house
[49.1]
[49.2]
chair
[55.1]
dog
car
aardvark

#only alpha
grep '[[:alpha:]]' <<< "$list"
cat
horse
MOUSE
Cow
house
chair
dog
car
aardvark

#start with c
grep '^c' <<< "$list"
cat
chair
car

#end with e
grep 'e$' <<< "$list"
horse
house

#first char of each item in list
grep -oP "^\K." <<< "$list"
[
c
h
M
[
h
[
[
c
[
d
c
2
2
1
a

#starts with upper case
grep "^[[:upper:]]" <<< "$list"
MOUSE
Cow

grep '^[A-Z]' <<< "$list"
MOUSE
Cow

#2 items after match
grep -A 2 '\[12.1\]' <<< "$list"
[12.1]
cat
horse

#does not contain a-z
grep -v '[A-Za-z]' <<< "$list"
[12.1]
[12.3]
[49.1]
[49.2]
[55.1]
26
28
132

#does not contain digit
grep -v '[0-9]' <<< "$list"
cat
horse
MOUSE
Cow
house
chair
dog
car
aardvark

#count matches
grep -c '[0-9]' <<< "$list"
8

#items that are 3 char long
grep '^...$' <<< "$list"
cat
Cow
dog
car
132

#multiple patterns
grep '^c\|h' <<< "$list"
cat
horse
house
chair
car

#search for blank lines(there are 2, top and bottom of $list)
grep '^$' <<< "$list"That's a start.
Anyone else is welcome to post more examples in this grep/egrep thread if you want.

See: man greplatest?d=yIl2AUoC8zA latest?i=XWUC0mpQKR4:jrDH0OuAi3A:F7zBnMy latest?i=XWUC0mpQKR4:jrDH0OuAi3A:V_sGLiP latest?d=qj6IDK7rITs latest?i=XWUC0mpQKR4:jrDH0OuAi3A:gIN9vFwXWUC0mpQKR4
External Content
Source RSS or Atom Feed
Feed Location https://feeds.feedburner.com/linuxquestions/latest
Feed Title LinuxQuestions.org
Feed Link https://www.linuxquestions.org/questions/
Reply 0 comments