bash sed 用字符替换空行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22263664/
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 09:50:42  来源:igfitidea点击:

sed replace empty line with character

bashsedawk

提问by cebach561

How do you replace a blank line in a file with a certain character using sed?

如何使用 sed 用某个字符替换文件中的空行?

I have used the following command but it still returns the original input:

我使用了以下命令,但它仍然返回原始输入:

sed 's/^$/>/' filename

Original input:

原始输入:

ACTCTATCATC

CTACTATCTATCC

CCATCATCTACTC

...

Desired output:

期望的输出:

ACTCTATCATC
>
CTACTATCTATCC
>
CCATCATCTACTC
>
...

Thanks for any help

谢谢你的帮助

回答by jaypal singh

Here is a way with awk. This wouldn't care if you have spaces or blank lines:

这是awk. 如果您有空格或空行,这不会在乎:

awk '!NF{
$ cat -vet file
ACTCTATCATC$
      $
CTACTATCTATCC$
$
CCATCATCTACTC$
       $
=">"}1' file

NFstands for number of fields. Since blank lines or lines with just spaces have no fields, we use that to insert your text. 1triggers the condition to be trueand prints the line:

NF代表字段数。由于空行或只有空格的行没有字段,我们使用它来插入您的文本。1触发条件为true并打印该行:

Test:

测试:

$ awk '!NF{
sed 's/^\s*$/>/' filename
=">"}1' file ACTCTATCATC > CTACTATCTATCC > CCATCATCTACTC >

$are end of line markers

$是行尾标记

sed 's/^[[:blank:]]*$/>/' filename

回答by Firas Moalla

You may have tabs or white spaces in your filename' empty lines, try the following:

filename' 空行中可能有制表符或空格,请尝试以下操作:

sed -i  's/^[[:space:]]*$/string/' foo

回答by Raman Shah

You may have whitespace in your input. First thing to try is:

您的输入中可能有空格。首先要尝试的是:

sed 's/^$/\>/g' filename

回答by sridharn

The following code should work:

以下代码应该可以工作:

sed '/^$/d' filename

回答by kisHoR

What's missing here is the escape character. This will work for you.

这里缺少的是转义字符。这对你有用。

##代码##

And if you need to delete the empty lines and print others, Try

如果您需要删除空行并打印其他行,请尝试

##代码##