Extract lines from files with names begining with given letter

Got here a list of columns, as follows:

59  LOUIS   1202    +1
60  FREDDIE 1201    +4
61  FINLAY  1200    -2
62  LEON    1137    +12
63  HARLEY  1132    +6
64  DAVID   1127    -1
65  MOHAMMAD1100    +6
66  REECE   1095    -1
67  KIAN    1090    0
68  KAI     1056    -6
69  KYLE    1030    -18
70  BRANDON 1011    -4
71  HAYDEN  1006    +5
72  ZACHARY 995     +10
73  KIERAN  973     -12
73  LUCA    973     -1
75  ASHTON  954     +4
76  BAILEY  939     -6
77  JAKE    913     +10
78  GABRIEL 910     +14
79  SAM     900     -2
80  EVAN    890     0
81  BRADLEY 847     -13

How could be extracted only the lines with, for example, letter “L”, as follows:

73  LUCA    973     -1
Asked By: Rubem74

||

That seems to be duplicated, but anyway, if it was understood, one may do it as follows:

First, save the list in a some nameslist.txt file, then:

sed -rn '/^[^s]+s+[F]/p' list.txt > result.txt, which should return following output in result.txt file:

60 FREDDIE 1201 +4
61 FINLAY 1200 -2

Answered By: Renan41
awk '$2 ~ /^L/' file

Tells awk to test the second field $2 using the regex ~ expression ^L and print the matching lines.

The regex matches the second field ($2) when it starts ^ with L

Answered By: bu5hman

Building on @bu5hman’s answer: With awk, you can easily pass the letter as a parameter:

awk -v letter="L" 'substr($2, 1, 1) == letter' file
# or with a constructed regex
awk -v letter="L" '$2 ~ "^" letter' file
Answered By: glenn jackman

Assuming that you have that list in list.txt, you can do the following:

 grep -h L list.txt > list_L.txt 

Explanation: grep L list.txt gives you all the lines containing an uppercase L. The option -h suppresses the output of the file name, but is only necessary if you are searching through multiple files (e.g. grep -h L lis*.txt). Adding > list_L.txt redirects the lines to the specified file.

If the L must only occur at the beginning of a “word” (on name, in this case), you need to tweak the above command a bit:

 grep -h '<L' list.txt > list_L.txt 

Adding < matches the beginning of a “word”, so <L selects lines containing a word beginning with an uppercase L.

Answered By: Tsundoku

Avoid RegEx when possible. AWK example:

index($2, "L") == 1
Answered By: user327359

Another grep example:

grep -E "[0-9]+ +L" file

+ matches one or more occurrence of the previous character, so in this case we match at least one numeric character, and at least one space, followed by a capital L.

-E is required to interpret the + as a special character instead of a literal ‘+’

output:

59  LOUIS   1202    +1
62  LEON    1137    +12
73  LUCA    973     -1
Answered By: F. Pareto