I have code that does something like this:
#!/bin/sh
CONTENTS=$(cat "somefile")
RELEVANT_LINES=$(echo "$CONTENTS" | grep -E "SEARCHEXPR")
COUNT=$(echo "$RELEVANT_LINES" | wc -l)
I hit an annoyance that this code didn't output the same if there weren't any matches, compared to the correct output given by replacing the third line with :
COUNT=$(echo "$CONTENTS" | grep -E "SEARCHEXPR" | wc -l)
I eventually traced to the fact that when there weren't any matches, RELEVANT_LINES was being set to the empty string, and echo was outputting a one line empty string + \n for a line count of 1.
I tried using printf and echo -n in the 3rd line, but couldn't find the elegant workaround and ended up using COUNT=$(echo "$RELEVANT_LINES" | grep '0' | wc -l)
(all lines contain a zero) to avoid having to regex filter the entire source file twice.
That can't be right, but I can't figure the correct fix.
I didn't drop to scripting with -eq ''
because I wasn't sure it would be as robust and I prefer piping directly to wc
for pure neatness.
Any hints how to get file content in a variable, to neatly distinguish zero vs one line after being filtered by grep? :)
COUNT=$(grep -Ec "SEARCHEXPR" somefile)
? – steeldriver Jan 14 '18 at 13:36