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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:24:25  来源:igfitidea点击:

Bash: replace empty line with string

bash

提问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

You can use sed:

您可以使用sed

sed -i -e 's/^$/second/' file

The -ioption toggles the in-place replacement.

-i选项切换就地替换。

回答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