bash 脚本逐行读取并回显到文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17071834/
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
bash script read line by line and echo to file
提问by user2479436
I can't get this script to do what I want. Can someone help it's supposed to read a text file line by line and then echo the result into another file. But it's not doing recognizing the blank line. As it supposed to print the line unless it's blank then it's suppose to print to the file.
我无法让这个脚本做我想做的事。有人可以帮助它逐行读取文本文件,然后将结果回显到另一个文件中。但它并没有识别空行。因为它应该打印该行,除非它是空白的,所以它应该打印到文件中。
iname = checktest
while read line
do
if [ "$line" == "" ];
then
echo "<blank>" >> $iname2.txt
else
echo "$line" >> $iname2.txt
fi
done <$iname.txt
回答by jaypal singh
You cannothave spaces between variable assignment in bash.
你不能让bash变量赋值之间的空间。
#!/bin/bash
iname=checktest #Should be no space between = sign
while read line; do
if [ -z "$line" ]; then
echo "I saw an empty line ... will report this"
else
echo "$line"
fi
done <"$iname".txt > newfile.txt
Also, use >after the end of loop. This prevents unnecessary I/O to open the file for writing during each loop cycle.
另外,>在循环结束后使用。这可以防止不必要的 I/O 在每个循环周期中打开文件进行写入。
回答by nitin
make some edits like this :
做一些这样的编辑:
iname = checktest
iname = 检查测试
while read line
do
if [ -z "$line" ]
then echo "" >> ${iname}2.txt
else
echo "$line" >> ${iname}2.txt
fi
done < ${iname} ;
it should work now , hope this helps ...
它现在应该可以工作了,希望这会有所帮助...
回答by Franko
iname = checktest
while read line
do
if [ "$line" != "" ];
then
echo $line >>
fi
done < $iname > ${iname}2.txt
It seems more logic to me to do something when it match only.
对我来说,仅在匹配时做某事似乎更合乎逻辑。

