bash在逐行遍历文件时跳过空行

我通过逐行遍历文件并将每个单词放入一个数组,并且工作。 但它也拾取空行,并将其作为一个项目在数组中,我怎样才能跳过空行?

示例文件

Line 1 line 2 line 3 line 4 line 5 line 6 

我的代码

 while read line ; do myarray[$index]="$line" index=$(($index+1)) done < $inputfile 

可能的伪代码

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

先用sed删除空行。

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

更优雅:

 echo "\na\nb\n\nc" | grep -v "^$" cat $file | grep -v "^$" | next transformations... 

在伪代码中执行相同的测试:

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

如果-z测试为true if empty表示为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 

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

我知道它已经解决了,但是,我需要输出数字的行,而忽略空行,所以我想把它放在这里,以防有人需要它。 🙂

使用grep删除空行:

 for word in $(cat ${inputfile} | grep -v "^$"); do myarray[$index]="${word}" index=$(($index+1)) done 

与调用sedgrep等外部命令的解决方案相比,这个版本非常快。 也是跳过只包含空格的行,行不需要为空就可以跳过。

 #!/bin/bash myarray=() while read line do if [[ "$line" =~ [^[:space:]] ]]; then myarray+=("${line}") fi done < test.txt for((i = 0; i < ${#myarray[@]}; ++i)) do echo ${myarray[$i]} done