Вот другой способ с sed
, который заменяет только первую пустую строку без использования \n
в RHS или расширения gnu sed
0 address:
sed '/^$/{ # if line is empty
x # exchange pattern space w. hold space
//{ # if pattern space is empty (means the hold buffer was empty)
s//%/ # replace it with a % character
h # overwrite hold space (so now hold space looks like this: ^%$)
s/$/ ghi/ # add a space and the string ghi after the %, then
G # append content of hold buffer to pattern space so now the
} # pattern space looks like this: ^% ghi\n%$
//!x # if pattern space is not empty it means a change was
} # already made so exchange back (do nothing)
' infile
one liner:
sed -e'/^$/{x;//{s//%/;h;s/$/ ghi/;G' -e'}' -e'//!x' -e'}' infile
Хотя на самом деле, это кусок пирога для ed
:
ed -s infile <<< $'/^$/s//% ghi\\\n%/\n,p\nq'
замените ,p
на w
для редактирования файла на месте.