0

For example, let's say I have a file "athletes" with the lines

1995-05-30-John-Smith 
1992-John-30-Smith-10 

How could I list the first 2 words of the lines that end in "Smith" and the last one, changing the format to # at the same time:

So the output would be:

1995#05#Smith
1
  • If you really want "lines that end in Smith", make sure you don't have any trailing whitespace. – glenn jackman Nov 4 '19 at 16:32
1

You can use awk like:

awk -F'-' '/Smith$/{print $1"#"$2"#"$NF}' athletes

It will give output:

1995#05#Smith

Here awk will search for the lines ending with Smith, and it will the print first, second and last field with #, in between them.

Using sed

sed -En 's/([^-]*)-([^-]*).*Smith$/\1#\2#Smith/gp' file.txt

It will match until first two - occurs, and then will print only matching lines after modifying them.

2
  • If I want to do for one more word for example ending in "Smith" or "William" is there anyway to do it in just one command? – MADS Nov 1 '19 at 17:25
  • @MADS you can use simple or condition, i.e. use /Smith$/ || /William$/ instead of /Smith$/. Tell me after using this. – Prvt_Yadav Nov 2 '19 at 10:15
0

You can try this:

grep "Smith$" file | tr "-" "#" | cut -d'#' -f1,2,5

Output:

1995#05#Smith
0

We can do it below by simple command too

 awk -F "-" '/Smith$/&&OFS="#"{print $1,$2,$NF}' file

output

1995#05#Smith
1
  • Why are you doing a variable assignment as part of the condition? I would define OFS as a command line argument with the -v switch. – glenn jackman Nov 4 '19 at 16:31

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.