使用 sed 反转 Switch 语句
Switch statement reverse using sed
我的代码如下所示:
switch (argument0) {
case ("Goblin"):
return 0;
break;
case ("Fang"):
return 1;
break;
...
}
我如何使用 sed 或其他命令行工具来切换 returns 和大小写,使其看起来像这样:
switch (argument0) {
case (0):
return "Goblin";
break;
case (1):
return "Fang";
break;
...
}
类似于
sed '/^[[:space:]]*case/ { N; s/case (\(.*\)):\(.* return \)\(.*\);/case ():;/; }' filename
即:
/^[[:space:]]*case/ { # in lines that bein with "case" (optionally preceded by
# whitespace)
N # fetch the next line
# Then split, reassemble.
s/case (\(.*\)):\(.* return \)\(.*\);/case ():;/
}
请注意,这仅适用于格式与您显示的代码相当严格的代码,return
直接位于 case
标签后的行中,括号恰到好处。
顺便说一句,我想不出在 C 中的 return
语句之后直接添加 break;
的理由。
使用 GNU awk 进行多字符 RS:
$ gawk -vRS="^$" -vORS= '{[=10=]=gensub(/(case \()([^)]+)(\):\s*return )(\S+);/,"\1\4\3\2;","g")}1' file
switch (argument0) {
case (0):
return "Goblin";
break;
case (1):
return "Fang";
break;
...
}
在正则表达式中随意添加 \s*
s if/when 白色 space 可能会出现。
sed '/^[[:space:]]*case/ {N;s/\(.*\)\("[^"]*"\)\(.*return \)\([^;]*\);/;/;}' YourFile
- 与@Wintermute 相同的概念,但使用其他分隔符。
- 这种 sed 永远不会安全(编码的可能性如此之大),但如果源文件与样本相似,则可以完成大部分工作。
我的代码如下所示:
switch (argument0) {
case ("Goblin"):
return 0;
break;
case ("Fang"):
return 1;
break;
...
}
我如何使用 sed 或其他命令行工具来切换 returns 和大小写,使其看起来像这样:
switch (argument0) {
case (0):
return "Goblin";
break;
case (1):
return "Fang";
break;
...
}
类似于
sed '/^[[:space:]]*case/ { N; s/case (\(.*\)):\(.* return \)\(.*\);/case ():;/; }' filename
即:
/^[[:space:]]*case/ { # in lines that bein with "case" (optionally preceded by
# whitespace)
N # fetch the next line
# Then split, reassemble.
s/case (\(.*\)):\(.* return \)\(.*\);/case ():;/
}
请注意,这仅适用于格式与您显示的代码相当严格的代码,return
直接位于 case
标签后的行中,括号恰到好处。
顺便说一句,我想不出在 C 中的 return
语句之后直接添加 break;
的理由。
使用 GNU awk 进行多字符 RS:
$ gawk -vRS="^$" -vORS= '{[=10=]=gensub(/(case \()([^)]+)(\):\s*return )(\S+);/,"\1\4\3\2;","g")}1' file
switch (argument0) {
case (0):
return "Goblin";
break;
case (1):
return "Fang";
break;
...
}
在正则表达式中随意添加 \s*
s if/when 白色 space 可能会出现。
sed '/^[[:space:]]*case/ {N;s/\(.*\)\("[^"]*"\)\(.*return \)\([^;]*\);/;/;}' YourFile
- 与@Wintermute 相同的概念,但使用其他分隔符。
- 这种 sed 永远不会安全(编码的可能性如此之大),但如果源文件与样本相似,则可以完成大部分工作。