1

(using MacOSX and may convert this to a perl script). I'm fairly new to Linux/Unix commands, and my Google search has been unsuccessful.

I am creating a script to make it fast to search for a record of someone's training. The way I'm doing this is listing the individual's training records in one line (perhaps there's a better way?). When I use Grep to search for a specific name, position trained in, or date, it shows the entire line. I want to grep search for a specific string and show only the beginning of the line, IE: first 2 words (First name / last name.).

The Training.txt file looks similar to this:

Ivie, Shawn Cashier 5/24/2016 Storeroom 12/2/2016 Service-Desk 11/31/2016

Allen, Adam Cashier 5/10/2016 Storeroom 12/13/2016

Martinez, Jessica Cashier 5/20/2017 Storeroom 10/29/2016 Supervisor 1/23/2016

The command I use now is: grep "Cashier" Training.txt

which returns all 3 records, the entire line contents of all records.

I've tried: grep -E -o ".{0,0}Cashier.{0,5}" Training.txt

which returns (in this example, all 3 records) but showing zero characters before "Cashier" and 5 after.

Cashier 5/10

How can I incorporate a grep (or perhaps a Perl command) to search for say, "Supervisor" and only show the first 2 words (names)? Secondary: any ideas that may make this type of process easier? (Spreadsheet is just not useful in this case).

2

This is perfect for awk:

awk '/Supervisor/ { print $1, $2 }' /path/to/inputfile

You can even restrict the search to the third field so that you don't get a false positive for someone named "Supervisor Bob":

awk '$3 ~ /Supervisor/ { print $1, $2 }' /path/to/inputfile
  • However, it would still fail for de la Vallée Poussin, Charles-Jean Étienne Gustave Nicolas Le Vieux Supervisor, or even for Fotherington Thomas, Basil Cashier. Technically, dealing with names is a problem that is still open to this day. – Satō Katsura May 24 '17 at 15:41
  • True, but that's what you get for using both spaces and commas as field delimiters. GIGO. – DopeGhoti May 24 '17 at 15:42
0

You can use grep with the Perl mode on:

grep -oP '^(\S+,?\s+){2}(?=Cashier\s)'

Results

Ivie, Shawn
Allen, Adam
Martinez, Jessica

Working

  • In Perl mode, grep is looking for two fields (\S+) from the beginning of line.
  • And standing at the end of the whitespace of the 2nd field, if we are able to see a Cashier followed by a whitespace, we've found our match. Since, the Cashier string is as a lookaround, it won't be included in the match.
  • Trying your syntax, it's not working...missing something? – Ivus May 29 '17 at 15:55
  • @Ivus MacOS X grep is not GNU. In that case, try using ggrep. – user218374 May 29 '17 at 20:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.