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

时间:2014-02-27 21:33:53

标签: 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

6 个答案:

答案 0 :(得分:21)

更优雅:

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

cat $file | grep -v "^$" | next transformations...

答案 1 :(得分:15)

实施与伪代码相同的测试:

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

-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

答案 2 :(得分:3)

首先使用sed删除空白行。

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

答案 3 :(得分:3)

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

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

答案 4 :(得分:2)

使用grep删除空行:

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

答案 5 :(得分:1)

与调用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
相关问题