Unix help to find blank lines in a file and print numbers on that line

Hi,
I would like to know how to solve one of my problems using expert unix commands.

I have a file with occasional blank lines;
for example;

dertu
frthu
fghtu

frtty
frtgy
frgtui

frgtu
ghrye
frhutp
frjuf

I need to edit the file so that the file looks like this;
1
dertu
frthu
fghtu
2
frtty
frtgy
frgtui
3
frgtu
ghrye
frhutp
frjuf
************
That is: I want to grep or find the blank line and sequentially number the blank lines and print that number in the blank space.

Hope you guys understood what I wanted.

Please let me know the best way for doing this;

Lucky Ali

Hi.

awk '
/^$/ { print ++C; next} 1
' input_file

Thank you very much
It worked perfectly
Lucky Ali

Shorter :rolleyes:

awk '$0=($0)?$0:++c' file

I'm not one to use things like LOL, LMAO, etc. But just for you:

ROFL!!!!

And it's only shorter because you didn't use spaces and your filename was shorter :slight_smile:

Shorter:

awk '$0=($0)?$0:++c' f

Thank you.
Your solution simplified

awk '!NF{$0=++c}1' file

There is always more than one way to solve a problem :cool:

And that's the beauty of it.

There's a lot to be said for the "concise but readable" option though.

When you can buy a 1.5 TB disk for 139 Swiss Francs, where's the harm in adding some white-space?!

Hi!

Still :slight_smile: one way to skin the cat:

sed -n "/^$/ ="

pen

Can you explain :confused:

First of all, as mentioned in the "Edit" part of my last posting, my solution does not provide a proper answer to the original question - the requirement was to number sequentially (1,2,3...) the blank lines.

The mentioned sed command matches blank lines and replaces them with the current line number. Hence, the the following

a

b

c

will be printed out as

a
2
b
4
c

pen

awk '{ print NF ? $0 : ++n }'