Bash:用字符串替换空行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16508701/
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: replace empty line with string
提问by Dawid
How to replace blank line in text file, let's say that file is:
如何替换文本文件中的空行,假设该文件是:
first
third
with some string( for ex. "second" ) using Bash? I wanna make sth. like this:
使用 Bash 使用一些字符串(例如 "second" )?我想做某事。像这样:
first
second
third
回答by Gumbo
回答by Yang
You can also use a default valuefor an unset or empty variable:
您还可以为未设置或空变量使用默认值:
cat file.txt | while read line
do
echo "${line:-second}" # empty lines are default to 'second'
done > file.out
回答by Bill
You can use [ -z "$line" ]to test if your lineis empty and do whatever you want with it.
您可以使用它[ -z "$line" ]来测试您line是否为空并使用它做任何您想做的事情。
cat file.txt | while read line
do
if [ -z "$line" ]
then
//$line is empty
fi
done
EDIT -- if you want to replace the empty line with "second" -- so you will end up with file.outwhich is the new file with empty lines replaced with second
编辑——如果你想用“第二个”替换空行——那么你最终会得到file.out哪个空行被替换的新文件second
touch file.out
cat file.txt | while read line
do
if [ -z "$line" ]
then
echo "second" >> file.out
else
echo $line >> file.out
fi
done

