Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a file after grep just if it founds the content?

Tags:

grep

shell

I'm doing this (e.g.:):

grep a text.txt > file.log

I can generate the file.log just if it founds the "a". Should I put it into a if? How? Can someone please give me an example? At this time this is generating blank files.

like image 745
letakeda Avatar asked Feb 03 '26 07:02

letakeda


2 Answers

A simple workaround would be to say:

grep a text.txt > file.log || rm file.log

This would remove file.log if grep didn't find a match. So you won't have blank files.

like image 91
devnull Avatar answered Feb 05 '26 05:02

devnull


awk '/a/{print >"file.log"}' text.txt

this command will create file.log if the file text.txt has a match with 'a'

like image 25
Vijay Avatar answered Feb 05 '26 05:02

Vijay



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!