0

I've parsed a file but there's some issue and a quick way around is to replace empty line with line below it so how do I do that

like the folowing file

apple

banana
big
sig

cake

should convert to

apple
banana
banana
big
sig
cake
cake
  • Would removing blank lines not work? – ctrl-alt-delor May 27 at 21:34
  • No, actually there are two files which need to be pasted side by side.. and one of the file is facing this issue.. – vib_29 May 28 at 11:10
3

You can do this in awk with its getline() function. The command works by selecting the empty lines in the text file !NF i.e. which means those lines that are empty (number of fields within the line is 0). Using the getline() function we get the next immediate line from the empty line and store in the variable nxt.

awk '!NF && ((getline nxt) >0){ $0 = nxt ORS nxt }1' file

Then the part within {..} constructs a line combining the variable, an embedded new-line ( string concatenation with ORS ) and the variable back again. The 2nd append is needed, because getline() call by default advances the line pointer by one level. See How to permanently change a file using awk? (“in-place” edits, as with “sed -i”) to change the file dynamically.

4

With sed:

sed -ne '/./!{n;p;}' -e p your-file

/./! action runs the action (here retrieve the next line and print it) for the lines that do not (!) contain any single character (. is the regex operator that matches any single character).

Some sed implementations also have a -i or -i '' option to edit the file in-place.

1
$ awk '/^$/ { ++r; next } { print; for (i=0; i<r; ++i) print; r=0 }' file
apple
banana
banana
big
sig
cake
cake

or

awk '/^$/ { ++r; next } { print; while (r > 0) { print; --r } }' file

which gives the same output.

This prints each line 1 time, plus the number of times corresponding to the number of blank lines above it. The blank lines are counted in the variable r.

Blank lines are detected with the regular expression ^$, but you could also use length == 0 or NF == 0.

1

Tried with below sed command combination and it worked fine

for i in `sed -n '/^$/{n;p}' filename`; do sed -i "0,/^$/s/^$/$i/g" filename; done

output

apple
banana
banana
big
sig
cake
cake
0

You may do this as follows:

$ sed -e ' /^$/{$!N' -e '}' -e 's/\n//p' inp
  • You appear to be using two different accounts (which is why your edit got put into a review queue). I'd recommend you merge them. – roaima May 27 at 20:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.