How to remove empty line.?

Hi gurus,

I have a script which works fine.

while read p
do
        [ -z "$para" ] && para="'${p}'" || para="${para},'${p}'"
done < file

a few days ago, there was issue pop up. in the file, there is empty line at end of the file which causes the list became 'a', 'b', 'c', '' .
I know I can remove the line with sed or other command. but just wondering if it is possible to add condition if p is '' then don't concanated.

thanks in advance.

Skip to the next loop cycle if $p is empty

while read p
do
  [ -z "$p" ] && continue
  para="${para:+$para,}'$p'"
done < file

The para= is a simple variant of your complex expression and works in all Posix compatible shells.

Another variation

while read p
do
  [ -n "$p" ] && para="$para,'$p'"
done < file
para=${para#,}

---
Small correction to MadeInGermany's suggestion:

para="${para:+"${para}",}'$p'"
2 Likes

Thanks, I have updated my code in post#2.

1 Like

Thanks Scrutinizer,
the code works. one more question raised while running the scrpt.
when running code, using "$p". it works.

while read p
do
[ -n "$p" ] && para="$para,'$p'"
done < file
para=${para#,}

when running code

 [ -n $p ], 

it doesn't work. the blank line is still there.

what's different between

[ -n $p ]

and

[ -n "$p" ]

?

You are welcome. If you try:

( set -x; [ -n $p ] && [ -n "$p" ])
+ '[' -n ']'
+ '[' -n '' ']'

You'll notice that the first one evaluates to -n and the second one to -n ''

In the first case the there is no protection of variable p, which contains an empty field. Since there is not protective quotes around $p , the result is field split and since $p is empty this results in 0 fields. So wat remains "-n" which is a test if the string "-n" is non empty
( [ "$somestring" ] if the same as [ -n "$somestring"] , I prefer the latter for clarity, so in fact [ -n ] is equivalent to [ -n -n ] )

In the second case the result of "$p" is not field split and so the -n is interpreted as an operator with one field as parameter, which contains an empty variable, and this evaluates to false .

So that is yet another reason to put quotes around variable expansions.

I hope this clarifies things...

1 Like

-n tests the following token for non-empty.
But the [ ] is a test command, and does not see the empty value of $p at all, but it sees a "" as an empty token.
The result for -n without a following token can be an error or the -n itself is seen as a token (and results in a true).
So far the [ ] test command.
For the [[ ]] compound the parser is different:
the $p is seen as a token regardless if its value is empty or not.
[[ -n $p ]] should work as you expect.

1 Like