search a file and create a new file only if a condition is met
Solution 1:
Tack a short circuit evaluation after grep
:
grep -q 'search_pattern' /file && : >/newfile
grep -q
produces no output on STDOUT, just exits with exit status0
if the pattern is found on the fileIf the pattern is found (
&&
), create a file/newfile
by: >/newfile
.
You could also go for the usual touch /newfile
approach, or on bash
, an empty redirection -- >/newfile
would do too.
Just to note, if the file already exists then touch
would only the change the relevant timestamps without truncating the file. And the empty redirection >/newfile
is not supported on all shells on-the-go (e.g. in zsh
), where you have to manually send the EOF.
Solution 2:
Just for fun:
python3 -c "if 'string' in open('logfile').read(): open('newfile', 'wt')"
where 'string'
is replaced by the string (condition), 'logfile'
is replaced by the path to the logfile, 'newfile'
is replaced by the actual path to the file to create, all in single quotes, lik in the example.
Solution 3:
You can use awk with its system()
command. If the /pattern/
is found, the codeblock {}
will be executed, in this case we call touch /tmp/my_file.txt
via system()
command.
The example below shows creating a temporary file if there is my user present in /etc/passwd
.
$ awk '/xieerqi/{system("touch /tmp/my_file.txt")}' /etc/passwd
$ ls -l /tmp/my_file.txt
-rw-rw-r-- 1 xieerqi xieerqi 0 1月 25 07:58 /tmp/my_file.txt
Alternatively, we could use redirection to file:
awk '/xieerqi/{f="/tmp/my_file.txt";print "" > f;close(f)}' /etc/passwd