1

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.

1

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}
           {print}'

Or:

cmd | sed '/pattern/!b
           w tmp
           d'

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

Or:

cmd | sed '/pattern/ {
             w tmp
             d
           }'

(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.

2

You can do this with pipes:

./myCMD | grep keyword > tmp

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

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.