[英]Switch statement reverse using sed
我有看起來像這樣的代碼:
switch (argument0) {
case ("Goblin"):
return 0;
break;
case ("Fang"):
return 1;
break;
...
}
如何使用sed或其他命令行工具在返回值和大小寫之間切換,如下所示:
switch (argument0) {
case (0):
return "Goblin";
break;
case (1):
return "Fang";
break;
...
}
遵循以下原則
sed '/^[[:space:]]*case/ { N; s/case (\(.*\)):\(.* return \)\(.*\);/case (\3):\2\1;/; }' 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 (\3):\2\1;/
}
請注意,這僅適用於嚴格按照您顯示的格式設置的代碼,並且return
直接位於case
標簽和括號后面的行中,是正確的方式。
順便說一句,我想不出break;
的理由break;
直接在C中的return
語句之后
對於多字符RS,使用GNU awk:
$ gawk -vRS="^$" -vORS= '{$0=gensub(/(case \()([^)]+)(\):\s*return )(\S+);/,"\\1\\4\\3\\2;","g")}1' file
switch (argument0) {
case (0):
return "Goblin";
break;
case (1):
return "Fang";
break;
...
}
如果/當可能出現空白時,在regexp中自由撒\\s*
s。
sed '/^[[:space:]]*case/ {N;s/\(.*\)\("[^"]*"\)\(.*return \)\([^;]*\);/\1\4\3\2;/;}' YourFile
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.