cebach561
cebach561

Reputation: 165

sed replace empty line with character

How do you replace a blank line in a file with a certain character using 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

Upvotes: 3

Views: 14747

Answers (5)

Kishor Unnikrishnan
Kishor Unnikrishnan

Reputation: 2609

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

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

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

sed '/^$/d' filename

Upvotes: 0

sridharn
sridharn

Reputation: 121

The following code should work:

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

Upvotes: 1

jaypal singh
jaypal singh

Reputation: 77185

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

awk '!NF{$0=">"}1' file

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

Test:

$ cat -vet file
ACTCTATCATC$
      $
CTACTATCTATCC$
$
CCATCATCTACTC$
       $

$ are end of line markers

$ awk '!NF{$0=">"}1' file
ACTCTATCATC
>
CTACTATCTATCC
>
CCATCATCTACTC
>

Upvotes: 6

Firas Moalla
Firas Moalla

Reputation: 132

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

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

Upvotes: 3

Raman Shah
Raman Shah

Reputation: 497

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

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

Upvotes: 2

Related Questions