Awk 实际上 具有 关联数组,所以我将采取的方法是:
1234563 .
对于#else 行,使用当前变量设置else 行号。
对于#endif,输出行号的任何详细信息,然后递减变量。
对于#elif,您需要结合#else 和#if 操作并确保相关的#end 关闭所有#if/#elif 行。 p>
例如,这是一个独立的 bash 脚本,展示了它的工作原理:
#!/usr/bin/env bash
# Use this script as input file as well, luckily C preprocessor
# macros look like bash comments.
#ifdef XYZZY
# Some text inside the first ifdef
#if 0
# This is the inner bit.
#endif
#if 1
# blah blah blah
#elif defined TWISTY
# yada yada yada
#elif defined PASSAGES
# run out of phrases
#else
# still got nothing
#endif
#else
#ifdef PLUGH
# This is the plugh stuff
#else
# This is the anti-plugh stuff
#endif
#endif
awk <$0 '
$1 == "#ifdef" || $1 == "#if" {
level++
line_mac[level] = $0
gsub(/^[ \t]+/, "", line_mac[level])
line_if[level] = NR
line_else[level] = "X"
line_end[level] = "X"
typ_elif[level] = 0
next
}
$1 == "#elif" {
line_else[level] = NR
level++
line_mac[level] = $0
gsub(/^[ \t]+/, "", line_mac[level])
line_if[level] = NR
line_else[level] = "X"
line_end[level] = "X"
typ_elif[level] = 1
next
}
$1 == "#else" {
line_else[level] = NR
next
}
$1 == "#endif" {
while (typ_elif[level] == 1) {
printf "if-line %-4s, else-line %-4s, endif-line %-4s, macro '%s'\n", line_if[level], line_else[level], NR, line_mac[level]
level--
}
printf "if-line %-4s, else-line %-4s, endif-line %-4s, macro '%s'\n", line_if[level], line_else[level], NR, line_mac[level]
level--
}
'
该输出(带有用于检查的文件中的编号行)是:
1: #!/usr/bin/env bash
2:
3: # Use this script as input file as well, luckily C preprocessor
4: # macros look like bash comments.
5:
6: #ifdef XYZZY
7: # Some text inside the first ifdef
8: #if 0
9: # This is the inner bit.
10: #endif
11: #if 1
12: # blah blah blah
13: #elif defined TWISTY
14: # yada yada yada
15: #elif defined PASSAGES
16: # run out of phrases
17: #else
18: # still got nothing
19: #endif
20: #else
21: #ifdef PLUGH
22: # This is the plugh stuff
23: #else
24: # This is the anti-plugh stuff
25: #endif
26: #endif
if-line 8 , else-line X , endif-line 10 , macro #if 0
if-line 15 , else-line 17 , endif-line 19 , macro #elif defined PASSAGES
if-line 13 , else-line 15 , endif-line 19 , macro #elif defined TWISTY
if-line 11 , else-line 13 , endif-line 19 , macro #if 1
if-line 21 , else-line 23 , endif-line 25 , macro #ifdef PLUGH
if-line 6 , else-line 20 , endif-line 26 , macro #ifdef XYZZY