Reputation: 49
i have this function that i am using in a script , in this function i read from a file and in this file i have lines that are empty , now i want to use grep on this file , but i don't know what to do if grep didn't find the wanted sentence , which means i want to compare to an empty line :
what i tried: i went to the files in my current directory and in each file i read line by line in order to remove extra spaces then i used grep on the current line , and if "abcd" does not exist in the current line then move to the next one.
function print_lines {
for file in *; do
while read f ; do
local line=`echo "$f"`
local x="`echo "$line" | grep -w "abcd"`"
if [[ "$x" != " " ]]; then
echo "i found "$x""
fi
done < "$file"
done
}
i know i am comparing $x to an empty line in a wrong way ! how can i do it corectly ?
also i can't use sed , awk ...
Upvotes: 0
Views: 117
Reputation: 881113
[[ "$x" != " " ]]
doesn't compare with an empty line, it compares with a single space. What you would need is something akin to [[ "$x" != "" ]]
.
However, bash
has specific tests for comparing empty strings:
[[ -z "${x}" ]]
You can test this with:
pax> str="$(echo hello | grep e)" ; [[ -z "${str}" ]] && echo empty
pax> str="$(echo hello | grep z)" ; [[ -z "${str}" ]] && echo empty
empty
However, this is all moot since bash
has the ability to search strings for simple things, without involving grep
at all(a):
pax> str=hello ; [[ ${str/e/} != ${str} ]] && echo has an e
has an e
pax> str=hello ; [[ ${str/z/} != ${str} ]] && echo has an z
The ${var/searchFor/replaceWith}
construct will modify the string if the search string was found (in our case, removing the matching text). So, if the modified string is different to the original, it means it contained what you were looking for.
(a) This is especially important when you're calling it a lot (as in within a line processing loop like here). Process start-up and tear-down is not free so, if you can avoid it, you'll find you can often get a performance boost.
Upvotes: 2
Reputation: 67467
what you need is just
$ if grep -wq "abcd" *; then echo "found"; fi
or
$ grep -wq "abcd" * && echo "found"
Upvotes: 1