我逐行遍历文件,并将每个单词放入一个数组,这是有效的.但它也会拾取空白行并将其作为数组中的项目,如何跳过空行?
示例文件
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)
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)
首先使用删除空白行sed。
for word in `sed '/^$/d' $inputfile`; do
myarray[$index]="$word"
index=$(($index+1))
done
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42600 次 |
| 最近记录: |