4

I am using grep to pull out lines that match 0. in multiple files. For files that do not contain 0., I want it to output "None" to a file. If it finds matches I want it to output the matches to a file. I have two example files that look like this:

$ cat sea.txt 
shrimp  0.352
clam    0.632
$ cat land.txt 
dog 0
cat 0

In the example files I would get both lines output from the sea.txt, but from the land.txt file I would just get "None" using the following code:

$ grep "0." sea.txt || echo "None" 

The double pipe (||) can be read as "do foo or else do bar", or "if not foo then bar". It works perfect but the problem I am having is I cannot get it to output either the matches (as it would find in the sea.txt file) or "None" (as it would find in the land.txt file) to a file. It always prints to the terminal. I have tried the following as well as others without any luck of getting the output saved to a file:

grep "0." sea.txt || echo "None" > output.txt
grep "0." sea.txt || echo "None" 2> output.txt

Is there a way to get it to save to a file? If not is there anyway I can use the lines printed to the terminal?

2 Answers 2

6

You can group commands with { }:

$ { grep '0\.' sea.txt || echo "None"; } > output.txt
$ cat output.txt
shrimp  0.352
clam    0.632

Notice the ;, which is mandatory before the closing brace.

Also, I've changed your regex to 0\. because you want to match a literal ., and not any character (which the unescaped . does). Finally, I've replaced the quotes with single quotes – this has no effect here, but prevents surprises with special characters in longer regexes.

Sign up to request clarification or add additional context in comments.

1 Comment

Nailed it. Thank you for that great answer.
0

how about this?

echo $(grep "0." sea.txt || echo "None") > output.txt

1 Comment

That would flatten the two lines from sea.txt onto one. You'd have to include double quotes around the $(…) to get it to do what's wanted. There'd also need to be the change in regex outlined in Benjamin's answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.