views:

335

answers:

4

I have a shell script like this:

cat file | while read line
do
    # run some commands using $line    
done

Now I need to check if the line contains any non-whitespace character ([\n\t ]), and if not, skip it. How can I do this?

+1  A: 

bash:

if [[ ! $line =~ [^[:space:]] ]] ; then
  continue
fi

And use done < file instead of cat file | while, unless you know why you'd use the latter.

Ignacio Vazquez-Abrams
I need smth that would work in both bash and sh. Is there any solution using sh/sed/tr (in case bash is not installed)?
planetp
A: 
if ! grep -q '[^[:space:]]' ; then
  continue
fi
Ignacio Vazquez-Abrams
+3  A: 

Since read reads whitespace-delimited fields by default, a line containing only whitespace should result in the empty string being assigned to the variable, so you should be able to skip empty lines with just:

[ -z "$line" ] && continue
Arkku
(More accurately, the delimiter used by `read` is determined by the `IFS` variable, which defaults to whitespace. Just unset `IFS` to revert to using whitespace.)
Arkku
All great is simple :)
planetp
A: 

@OP, cat i useless in this case if you are using while read loop. I am not sure if you meant you want to skip lines that is empty or if you want to skip lines that also contain at least a white space,

i=0
while read -r line
do
  ((i++)) # or $(echo $i+1|bc) with sh
  case "$line" in
    "") echo "blank line at line: $i ";;
    *" "*) echo "line with blanks at $i";;
    *[[:blank:]]*) echo "line with blanks at $i";;
  esac
done <"file"
ghostdog74