Ubuntu: search a file and create a new file only if a condition is met



Question:

I have a logfile and I want to search it for a string and only if that string is found a new file to be created. How can I achieve this, sed doenst seem to be fitting in this case.


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 status 0 if the pattern is found on the file

  • If 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   


Solution:4

You don't say whether the you want a new empty file, or if you need more complex processing to create the file.

If the former, the reply by @heemayl is spot on.

Otherwise, use an if-statement:

if grep -q 'search_pattern' /file  then      # Create your file here  fi  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »