bash: read line and keep spaces

我怕爱的太早我们不能终老 提交于 2019-11-30 09:02:50

问题


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


回答1:


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



回答2:


Following your code, it can be improved.

while read line; do
        if [ -z "$line" ]
        then
             echo "Fake empty line detected"
        fi
done < "$1"

The test -z checks if $line is empty.

Output:

Fake empty line detected
Fake empty line detected


来源:https://stackoverflow.com/questions/20776911/bash-read-line-and-keep-spaces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!