Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

bash: read line and keep spaces

I am trying to read lines from a file containing multiple lines. I want to identify lines that contain only spaces. By definition, an empty line is empty and does not contain anything (including spaces). I want to detect lines that seems to be empty but they are not (lines that contain spaces only)

    while read line; do
        if [[ `echo "$line" | wc -w` == 0 && `echo "$line" | wc -c` > 1 ]];
        then
             echo "Fake empty line detected"
        fi
    done < "$1"

But because read ignores spaces in the start and in the end of a string my code isn't working.

an example of a file

hi
 hi
(empty line, no spaces or any other char)
hi
  (two spaces)
hey

Please help me to fix the code

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Disable word splitting by clearing the value of IFS (the internal field separator):

while IFS= read -r line; do
....
done < "$1"

The -r isn't strictly necessary, but it is good practice.


Also, a simpler way to check the value of line (I assume you're looking for a line with nothing but whitespace):

if [[ $line =~ ^$ ]]; then
    echo "Fake empty line detected"
fi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...