Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to skip blank line when reading a text file?

Status
Not open for further replies.

volcano

Programmer
Aug 29, 2000
136
HK
Hello, I would like to write a script which will read a text file and do something. And I want to skip those blank lines or lines with spaces. How could I do so?

Thanks!
--------------------
(abc.txt)
111

222
333


(script.sh)
!/bin/sh
if [ -f $PWD/test.txt ]; then
cat test.txt | while read LINE
do
if [ -n $LINE ]; then
echo $LINE
fi
done
fi

---
I also tried "if [ $LINE != '' ]; then" statement, but still failed....
my expected result in screen would be :
111
222
333
 
Instead of...
[tt] cat test.txt | while read LINE[/tt]
You could try...
[tt] grep . test.txt | while read LINE[/tt]

And instead of...
[tt] if [ -n $LINE ]; then[/tt]
You could try...
[tt] if [ x$LINE != x ]; then[/tt]

 
Hi,
you can write
1.
if [ ${#LINE} -ne 0 ] ; then # ${#LINE} - length of $LINE
2. you can read your file:
for LINE in `cat test.txt`

in this case blank lines will be skiped.

Regards Boris
 
Or use awk

awk 'length' test.txt > new.txt

If you want to remove lines with white space

awk '/^[ ]*$/{next}{print}' test.txt > new.txt

where the square brackets contain a space and a tab. CaKiwi

"I love mankind, it's people I can't stand" - Linus Van Pelt
 
[tt]grep -v "^[ ]*$"[/tt]

-v = print lines *not* matching the regexp:

^ marking the beginning of a line
[ ] being a space
* indicating to match the previous item (a space) zero or more times
$ marking the end of a line
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top