Input file(s):
foo.bar.baz () ->
templateUrl: require('x.jade')
perl
command:
perl -i -0777pe '$_=~s/templateUrl:( \K.*)/templateUrl/;print"var templateUrl =$1\n"' *
Output file(s):
var templateUrl = require('x.jade')
foo.bar.baz () ->
templateUrl: templateUrl
Breakdown:
perl
scripting language that excels at text manipulation
-i
edit files in-place
-0777
work with the file as a whole, as opposed to line-by-line
p
print the file (in this case the file will be saved, due to the -i
switch)
e
execute the following command, as opposed to executing code that is saved in a file
'
start of instructions
$_=~s
perform a substitution on the entire file ($_
)
/templateUrl:( \K.*))/
look for a line matching the regex templateUrl: .*
, and capture the string matching the parenthesised subexpression .*
to a variable (called $1
by default)
templateUrl/
replace the part after the \K
marker in the matched line with text templateUrl
;
separates between instructions
print"var templateUrl =$1\n"
print var templateUrl =
, the contents of $1
and a newline
- at this point, the rest of the file is implicitly printed, because the
p
switch was specified
'
end of instructions
*
process every file in the current directory
There can be of course different approaches, such as:
perl -i -ne 'if ($_=~s/templateUrl:( \K.*)/templateUrl/){$a="templateUrl =$1"} {$file.=$_} END{print"var $a\n$file"}' *
AWK:
Since the question is about sed
or awk
, it is worth noting that either approach can be just as easily implemented in awk
:
awk -i 'BEGIN {RS="\0"} {match($0,/templateUrl:( .*)/,m); gsub("templateUrl: .*","templateUrl: templateUrl"); print "var templateUrl ="m[1]$0}' *
awk -i '/templateUrl: / {a="templateUrl = "$2;gsub("templateUrl: .*","templateUrl: templateUrl")} NR==1 {file=$0} NR==2{file=file"\n"$0} END{print a"\n"file}' *
1Excuse me if I didn't understand, see if this sed does what you want
sed -n '1h;:a;n;s/require/&/;tInsert;H;ba;:Insert;H;s/^/var/;s/:/ =/;G;s/: .*/: templateUrl/;p'
– Paulo – 2017-08-01T19:36:39.920@Paulo Nice
sed
solution. Please post it as an answer possibly adding some explanations. – simlev – 2017-08-02T11:16:24.280@simlev because I've been on holiday, I'm just catching up now. – user88974 – 2017-08-16T08:09:38.443