I have a command which will produce lots of output to STDOUT, which I know can be redirected into a file this way:

./myCMD 1>tmp

How can the output be filtered before redirecting it into the file. For example, I would want to redirect only those lines of output which contain some key word.


If you mean that you only want some lines to go to the tmp file, while the rest are left untouched:

cmd | awk '/pattern/ {print > "tmp"; next}


cmd | sed '/pattern/!b
           w tmp

(on one line: cmd | sed -e '/pattern/!b' -e 'w tmp' -e d)


cmd | sed '/pattern/ {
             w tmp

(on one line: cmd | sed -e '/pattern/{w tmp' -e 'd;}')

Note that for sed, pattern is a basic regular expression, while for awk, it's an extended regular expression.

| improve this answer | |

You can do this with pipes:

./myCMD | grep keyword > tmp

This will only write lines containing “keyword” to the tmp file.

If you want to see the full output, but only log a subset to a file, add tee (assuming your shell supports process substitution):

./myCMD | tee >(grep keyword > tmp)
| improve this answer | |
  • while i prefer grep, for some reason, didn't work for me on osx, but sed solution does – crollywood Sep 11 at 10:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.