庆典:读线和保持空间 [英] bash: read line and keep spaces

查看:134
本文介绍了庆典:读线和保持空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图读取包含多个行的文件行。我想确定只包含空格线。
根据定义,一个空行是空的,不包含任何(包括空格)。
我想要检测,这似乎是空行,但他们没有。

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"

但由于读忽略空格开始和在一个字符串的结尾我的code是行不通的。

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

的文件的一个例子

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

请帮我修复code

推荐答案

通过清除的 IFS (内部字段分隔符):

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

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

-r 不是绝对必要的,但它是很好的做法。

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

这篇关于庆典:读线和保持空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆