Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep / sed: How to print *something* when nothing matches

Tags:

grep

sed

awk

thanks for reading.

I have a plain text file with some simple user information

The thing is, sometimes one of those items is missing.

Notice how Norman and Reggie show an email addr, but Missy doesn't:

Name: Norman Normalrecord
Email: [email protected]
Addr: 123 Main street

Name: Missy Missington
Addr: 789 Back street

Name: Reggie Regularrecord
Email: [email protected]
Addr: 456 Middle street

I would like to grep / sed and say "If no email address is found, substitute with the text missing_email_addr", so I get this result :

Norman Normalrecord
[email protected]
123 main street

Missy Missington
MISSING_EMAIL_ADDR
789 back street

Reggie Regularrecord
[email protected]
456 middle street

The problem is, in all my experiments when nothing is found grep / sed produce absolutely nothing, so I can't even do a second pass to global-replace.

What I dream of is something like (obviously pseudo-grep) that provides what to print when a search doesn't find anything :

grep /Name:/MISSING_NAME/email:/MISSING_EMAIL_ADDR/Addr:/MISSING_STREET_ADDR/

Is there any way to do something like this? Thanks again.

like image 385
Sliced Bread Avatar asked Dec 07 '25 06:12

Sliced Bread


2 Answers

Here's a start. It replaces missing e-mail lines with "Email: N/A".

awk -v RS='\n\n' -v FS='\n' -v OFS='\n' \
    '{ if (!$3) $3 = "Email: N/A"; print; print "" }' users.txt

Output:

Name: Norman Normalrecord
Email: [email protected]
Addr: 123 Main street

Name: Missy Missington
Addr: 789 Back street
Email: N/A

Name: Reggie Regularrecord
Email: [email protected]
Addr: 456 Middle street
like image 83
John Kugelman Avatar answered Dec 09 '25 10:12

John Kugelman


This might work for you (GNU sed):

sed '/^Name: /!b;:a;$!N;/\nAddr: /!ba;/\nEmail: /!s/\n/&Email: MISSING_EMAIL_ADDR&/' file

If you want to remove the labels:

sed -r '/^Name: /!b;:a;$!N;/\nAddr: /!ba;/\nEmail: /!s/\n/&Email: MISSING_EMAIL_ADDR&/;s/(Name|Email|Addr): //g' file
like image 23
potong Avatar answered Dec 09 '25 09:12

potong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!