0

I need some help with some bash. I've only learnt like grep, awk, find, sed etc.

Say I have a file named people.txt with different names on a line on multiple lines but a name appears in every line. For example:

Ln1 - chris butcher, sam witwickie, joseph stalin, king kunta

Ln2 - Thor, ironman, mariah carey, chris butcher

Ln3 - jen love, chris butcher, jeep lake

How would I print chris butcher's name on each line? Note that chris butcher's name appear on different parts of the line

The expected result I would like is:

Ln1 - chris butcher

Ln2 - chris butcher

Ln3 - chris butcher

I know that grep -i "chris butcher" would highlight the names in each line but I need it to print just 'chris butcher' in each line as the result.

Thanks in advanced!

Raffa
  • 34,963

2 Answers2

0

This bash script should do the job:

#!/bin/bash

fileName="/path/to/file.txt" identifier="chris butcher" counter=1 while read oneLine; do if [[ "$oneLine" == "$identifier" ]]; then echo "Ln$counter - $identifier" ((counter++)) fi done < "$fileName" echo

Stormlord
  • 6,807
0

Given this input file:

Ln1 - chris butcher, sam witwickie, joseph stalin, king kunta
Ln2 - Thor, ironman, mariah carey, chris butcher
Ln3 - jen love, chris butcher, jeep lake

Using grep -o 'chris butcher' people.txt will output:

chris butcher
chris butcher
chris butcher

As @Raffa suggested in a comment, you might also want to make the condition to be more strict, match word expressions with -w, to avoid false matches such as "chris butcherfoo" or "foochris butcher". Also, your example had some line numbers, so the -n might also be interesting for you.

janos
  • 4,968