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
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
With sed
:
sed -ne '/./!{n;p;}' -e p your-file
/./! action
runs the action (here retrieve the n
ext line and p
rint 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.
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.
$ 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
.
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
You may do this as follows:
$ sed -e ' /^$/{$!N' -e '}' -e 's/\n//p' inp