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?

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Batwood
  • 91
  • 7

2 Answers2

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.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
0

how about this?

echo $(grep "0." sea.txt || echo "None") > output.txt
yftse
  • 183
  • 6
  • 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. – Jonathan Leffler Jan 16 '16 at 05:00