@ perl
da solução de simlev realmente tem menos etapas, mas gostaria de apresentar meu comando sed
. É mais relevante porque o OP já imaginou usar sed
e solicita explicitamente um script sed
ou awk
.
sed -n '1h;:a;n;s/require/&/;tInsert;H;ba;:Insert;H;s/^/var/;s/:/ =/;G;s/: .*/: templateUrl/;p'
Observação: este comando não funcionará se o arquivo contiver mais de uma linha com :
ou require
.
Explicação:
sed -n # -n option disables automatic printing.
1 h # h command puts the first line (address 1) in the hold space,
# replacing any previous content.
:a # Set a mark with label 'a'.
n # n command prints the pattern space and loads next line of input,
# replacing all pattern space content.
# But it will not print because of -n option.
s/require/&/ # Test if the pattern space has the line OP wants edit.
t Insert # If substitution was made, t command jumps to the mark with label 'Insert'.
H # If not, continue with H command, it appends a '\n' to the hold space content
# and then appends the pattern space to the hold space.
b a # b (branch) command, jumps to the mark with label 'a'.
:Insert # Exit from the 'a' loop. Here the hold space has all the lines that precede
# the line with 'replace', and pattern space has the line with 'replace'.
H # The line with 'replace' is appended to the hold space too.
s/^/var/ # Here sed finally edits the line, replacing the beginning with 'var' ...
s/:/ =/ # and only the first ':' with ' ='.
G # G command appends the content of hold space to the edited pattern space,
# here that line edited above in pattern space becomes the first line.
s/: .*/: templateUrl/ # One more substitution.
p' # Finally, print the pattern space.