我想在一组 C 源文件中搜索简单的 if
语句。
这些是以下形式的语句:
if (condition)
statement;
任何数量的空白或其他序列(例如“} else”)都可能出现在 if
之前的同一行中。注释可能出现在“if(条件)”和“statement;”之间。
我想排除以下形式的复合语句:
if (condition)
{
statement;
statement;
}
我在 awk 中尝试了以下各项:
awk '/if \(.*\)[^{]+;/ {print NR $0}' file.c # (A) No results
awk '/if \(.*\)[^{]+/ {print NR $0}' file.c # (B)
awk '/if \(.*\)/ {print NR $0}' file.c # (C)
(B) 和 (C) 给出了不同的结果。两者都包括我正在寻找的项目和我想要排除的项目。显然,部分问题在于如何处理跨越多行的模式。
可以忽略边缘情况(格式错误的注释、奇怪的缩进或奇怪位置的大括号等)。
我怎样才能做到这一点?
最佳答案
基于 Al 的回答,但修复了几个问题(另外我决定也检查简单的 else
子句(此外,它打印完整的 if block ):
#!/usr/bin/perl -w
my $line_number = 0;
my $in_if = 0;
my $if_line = "";
#ifdef NEW
my $block = "";
#endif /* NEW */
# Scan through each line
while(<>)
{
# Count the line number
$line_number += 1;
# If we're in an if block
if ($in_if)
{
$block = $block . $line_number . "+ " . $_;
# Check for open braces (and ignore the rest of the if block
# if there is one).
if (/{/)
{
$in_if = 0;
$block = "";
}
# Check for semi-colons and report if present
elsif (/;/)
{
print $if_line;
print $block;
$block = "";
$in_if = 0;
}
}
# If we're not in an if block, look for one and catch the end of the line
elsif (/(if \(.*\)|[^#]else)(.*)/)
{
# Store the line contents
$if_line = $line_number . ": " . $_;
# If the end of the line has a semicolon, report it
if ($2 =~ ';')
{
print $if_line;
}
# If the end of the line contains the opening brace, ignore this if
elsif ($2 =~ '{')
{
}
# Otherwise, read the following lines as they come in
else
{
$in_if = 1;
}
}
}
关于c - 如何在 C 源代码中搜索简单的 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1078767/