bash在逐行迭代文件时跳过空白行

MAX*_*GEN 15 bash

我逐行遍历文件,并将每个单词放入一个数组,这是有效的.但它也会拾取空白行并将其作为数组中的项目,如何跳过空行?

示例文件

      Line 1
line 2

line 3
        line 4 

line 5
   line 6
Run Code Online (Sandbox Code Playgroud)

我的代码

while read line ; do
            myarray[$index]="$line"
            index=$(($index+1))
    done < $inputfile
Run Code Online (Sandbox Code Playgroud)

可能的伪代码

while read line ; do
           if (line != space);then
            myarray[$index]="$line"
             fi
            index=$(($index+1))
    done < $inputfile
Run Code Online (Sandbox Code Playgroud)

Boh*_*dan 24

更优雅:

echo "\na\nb\n\nc" | grep -v "^$"

cat $file | grep -v "^$" | next transformations...
Run Code Online (Sandbox Code Playgroud)

  • 为什么`cat`要"grep"?不会`grep -v"^ $""$ inputfile"`也一样吗? (11认同)
  • 由于输出旨在通过管道传输到另一个操作,因此通过管道传输输入文件比将其作为参数提供更好。这样,您可以直接从左到右读取数据流,而不是从中间开始向左然后向右跳转。诚然,它浪费了 4 个字符和几毫秒,但我认为这没什么大不了的。此外,如果输入来自其他地方,以这种方式呈现它可以轻松地交换管道的第一阶段。 (3认同)

ise*_*dev 17

实现与伪代码中相同的测试:

while read line; do
    if [ ! -z "$line" ]; then
        myarray[$index]="$line"
        index=$(($index+1))
    fi
done < $inputfile
Run Code Online (Sandbox Code Playgroud)

-z测试手段true if empty.!否定(即如果不是空的话,则为真).

您还可以使用[ "x$line" = x ]或类似的表达式test "x$line" = x来测试该行是否为空.

但是,任何包含空格的行都不会被视为空.如果这是一个问题,您可以使用sed从输入中删除这些行(包括空行),然后将它们传递给while循环,如下所示:

sed '/^[ \t]*$/d' $inputfile | while read line; do
    myarray[$index]="$line"
    index=$(($index+1))
done
Run Code Online (Sandbox Code Playgroud)

  • 它可以是简单的:`if [ "$line" ]; 然后` (3认同)

SzG*_*SzG 6

首先使用删除空白行sed

for word in `sed '/^$/d' $inputfile`; do
    myarray[$index]="$word"
    index=$(($index+1))
done
Run Code Online (Sandbox Code Playgroud)


Kos*_*nos 5

cat -b -s file |grep -v '^$'

我知道它已经解决了,但是,我需要输出编号行,同时忽略空行,所以我想把它放在这里,以防有人需要它。:)