bash 逐行遍历文件时跳过空行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22080937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Skip blank lines when iterating through file line by line
提问by MAXGEN
I am iterating through a file line by line and put each word into a array and that works. But it also picks up blank lines and puts it as an item in the array, how can I skip the blank lines?
我正在逐行遍历一个文件,并将每个单词放入一个数组中,这样就可以了。但它也会拾取空行并将其作为数组中的一个项目,如何跳过空行?
example file
示例文件
Line 1
line 2
line 3
line 4
line 5
line 6
My code
我的代码
while read line ; do
myarray[$index]="$line"
index=$(($index+1))
done < $inputfile
Possible psuedo code
可能的伪代码
while read line ; do
if (line != space);then
myarray[$index]="$line"
fi
index=$(($index+1))
done < $inputfile
采纳答案by SzG
Remove the blank lines first with sed
.
先用 删除空行sed
。
for word in `sed '/^$/d' $inputfile`; do
myarray[$index]="$word"
index=$(($index+1))
done
回答by Bohdan
Be more elegant:
更优雅:
echo "\na\nb\n\nc" | grep -v "^$"
cat $file | grep -v "^$" | next transformations...
回答by isedev
Implement the same test as in your pseudo-code:
实现与伪代码相同的测试:
while read line; do
if [ ! -z "$line" ]; then
myarray[$index]="$line"
index=$(($index+1))
fi
done < $inputfile
The -z
test means true if empty
. !
negates (i.e. true if not empty).
该-z
检测手段true if empty
。!
否定(即如果不为空则为真)。
You can also use expressions like [ "x$line" = x ]
or test "x$line" = x
to test if the line is empty.
您还可以使用像[ "x$line" = x ]
或test "x$line" = x
这样的表达式来测试该行是否为空。
However, any line which contains whitespace will notbe considered empty. If that is a problem, you can use sed
to remove such lines from the input (including empty lines), before they are passed to the while
loop, as in:
但是,任何包含空格的行都不会被视为空行。如果这是一个问题,您可以使用sed
从输入中删除这些行(包括空行),然后再将它们传递给while
循环,如下所示:
sed '/^[ \t]*$/d' $inputfile | while read line; do
myarray[$index]="$line"
index=$(($index+1))
done
回答by Kostas Andrianos
cat -b -s file |grep -v '^$'
cat -b -s file |grep -v '^$'
I know it's solved but, I needed to output numbered lines while ignoring empty lines, so I thought of putting it right here in case someone needs it. :)
我知道它已经解决了,但是,我需要在忽略空行的同时输出编号的行,所以我想把它放在这里以防有人需要它。:)
回答by NFTX
Use grep to remove the blank lines:
使用 grep 删除空行:
for word in $(cat ${inputfile} | grep -v "^$"); do
myarray[$index]="${word}"
index=$(($index+1))
done
回答by Galik
This version is very fast compared to solutions that invoke external commands like sed
and grep
. Also it skips lines that contain only spaces, the lines don't need to be empty to be skipped.
与调用sed
和等外部命令的解决方案相比,此版本非常快grep
。此外,它会跳过仅包含空格的行,这些行不需要为空即可被跳过。
#!/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