Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modified copies of line sed / awk

Tags:

bash

sed

awk

I'm trying to insert modified copies of lines after the original lines.

Here's my file:

random
N:John Doe
random
N:Jane Roe
random
random
N:Name Sirname
random

Here's what my file need needs to look like:

random
N:John Doe
FN:John Doe
random
N:Jane Roe
FN:Jane Roe
random
random
N:Name Sirname
FN:Name Sirname
random

Any ideas for this one? Can't seem to find the right sed/awk combination...

like image 773
Henk Avatar asked Jan 11 '23 07:01

Henk


1 Answers

sed -n ' p; s/^N:/FN:/p' original.txt

This produces:

random
N:John Doe
FN:John Doe
random
N:Jane Roe
FN:Jane Roe
random
random
N:Name Sirname
FN:Name Sirname
random

It works as follows. We invoke sed -n which means that, by default, it won't print any lines. Then, we give it two commands. The first, p, is to print the existing line unmodified. The second, s/^N:/FN:/p, tells it to try to substitute FN: for any leading N: and, if that substitute succeeds (meaning that the line actually did start with N:), then also print the modified version.

like image 74
John1024 Avatar answered Jan 18 '23 00:01

John1024