If want to replace all:
if (err) {
callback(err);
return;
}
With:
if (err) return callback(err);
In my code.
Using sed, I was looking for something like:
sed -n '1h;1!H;${;g;s/if\s*\(err\)\s*{\s*callback\(err\);\s*return;\s*}/if \(err\) return callback\(err\);/g;p;}'
As described here: http://austinmatzko.com/2008/04/26/sed-multi-line-search-and-replace/
But it doesn't seems to work. Any idea?
I agree with other posters that there are better alternatives for sed
, but in case you are curious: the fault was in the parentheses. These should not be escaped with a backslash, as this causes them to be handled as grouping symbols, rather than literal parentheses.
This works fine:
sed -n '1h;1!H;${;g;s/if\s*(err)\s*{\s*callback(err);\s*return;\s*}/if (err) return callback(err);/g;p;}'
Through Perl,
$ cat file
foo
if (err) {
callback(err);
return;
}
bar
$ perl -0pe 's/(if *(\(err\))) *{\s*(callback)\2;\s*(return);\s*}/$1 $4 $3$2;/g' file
foo
if (err) return callback(err);
bar
使用perl,我能够做到:
perl -i -p0e 's/if \(err\) \{\n\s*callback\(err\)\;\n\s*return;\s*}/if \(err\) return callback\(err\)\;/smg' my_file
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.