我通过逐行遍历文件并将每个单词放入一个数组,并且工作。 但它也拾取空行,并将其作为一个项目在数组中,我怎样才能跳过空行?
示例文件
Line 1 line 2 line 3 line 4 line 5 line 6
我的代码
while read line ; do myarray[$index]="$line" index=$(($index+1)) done < $inputfile
可能的伪代码
用户空闲时间C windows和linux
远程Linux本地用户的空闲时间
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 "nanbnnc" | 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 '^$'
我知道它已经解决了,但是,我需要输出数字的行,而忽略空行,所以我想把它放在这里,以防有人需要它。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。