Reputation: 91
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?
Upvotes: 4
Views: 40
Reputation: 52316
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.
Upvotes: 6
Reputation: 193
how about this?
echo $(grep "0." sea.txt || echo "None") > output.txt
Upvotes: 0