我需要在很多*.c
文件中进行替换。我想像这样进行替换:
原文:printf("This is a string! %d %d\n", 1, 2);
结果:print_record("This is a string! %d %d", 1, 2);
也就是将“ printf
”替换为“ print_record
”,并删除尾随的“ \n
”。
起初,我习惯于sed
执行此任务。但是,可能存在以下情况:
printf("This is a multiple string, that is very long"
" and be separated into multiple lines. %d %d\n", 1, 2);
在这种情况下,我无法使用轻松sed
删除“ \n
”。我听说perl
可以很好地完成这项工作。但我对 还不熟悉perl
。所以有人能帮我吗?如何使用 完成这个perl
?
非常感谢!
答案1
您要做的事情并不简单。它需要进行一些解析来处理平衡分隔符、引号以及相邻字符串文字应合并为一个的 C 规则。幸运的是,Perl 模块文字::平衡处理了很多这样的问题(Perl 的“标准”库中有 Text::Balanced)。下面的脚本应该或多或少能满足你的要求。它接受一个命令行参数并在标准输出上输出。你必须把它包装在 shell 脚本中。我使用了以下包装器来测试它:
#/bin/bash
find in/ -name '*.c' -exec sh -c 'in="$1"; out="out/${1#in/}"; perl script.pl "$in" > "$out"' _ {} \;
colordiff -ru expected/ out/
这是 Perl 脚本。我写了一些注释,但如果您需要更多解释,请随时询问。
use strict;
use warnings;
use File::Slurp 'read_file';
use Text::Balanced 'extract_bracketed', 'extract_delimited';
my $text = read_file(shift);
my $last = 0;
while ($text =~ /( # store all matched text in $1
\bprintf # start of literal word 'printf'
(\s*) # optional whitespace, stored in $2
(?=\() # lookahead for literal opening parenthesis
)/gx) {
# after a successful match,
# 1. pos($text) is on the character right behind the match (opening parenthesis)
# 2. $1 contains the matched text (whole word 'printf' followed by optional
# whitespace, but not the opening parenthesis)
# 3. $2 contains the (optional) whitespace
# output up to, but not including, 'printf'
print substr($text, $last, pos($text) - $last - length($1));
print "print_record$2(";
# extract and process argument
my ($argument) = extract_bracketed($text, '()');
process_argument($argument);
# save current position
$last = pos($text);
}
# output remainder of text
print substr($text, $last);
# process_argument() properly handles the situation of a format string
# consisting of adjacent string literals
sub process_argument {
my $argument = shift;
# skip opening parenthesis retained by extract_bracketed()
$argument =~ /^\(/g;
# scan for quoted strings
my $saved;
my $last = 0;
while (1) {
# extract quoted string
my ($string, undef, $whitespace) = extract_delimited($argument, '"');
last if !$string; # quit if not found
# as we still have strings remaining, the saved one wasn't the last and should
# be output verbatim
print $saved if $saved;
$saved = $whitespace . $string;
$last = pos($argument);
}
if ($saved) {
$saved =~ s/\\n"$/"/; # chop newline character sequence off last string
print $saved;
}
# output remainder of argument
print substr($argument, $last);
}