10

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.

2
  • 3
    Use grep to search. The -q option will suppress all output, and return match/nonmatch via grep's exit code, which is easily testable.
    – waltinator
    Jan 25, 2017 at 14:44
  • 2
    It might be helpful to tell us what the condition is.
    – j0h
    Jan 25, 2017 at 15:23

4 Answers 4

16

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.

3
  • What does the : do ? Jan 25, 2017 at 16:37
  • 5
    @George : is shorthand for true, it's a no-op command that always exits with exit status 0.
    – heemayl
    Jan 25, 2017 at 16:39
  • @heemayl This worked best till this day
    – Jacknife
    Feb 3, 2017 at 16:51
6

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.

4

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 
0

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .