I have code that looks like this:
switch (argument0) {
case ("Goblin"):
return 0;
break;
case ("Fang"):
return 1;
break;
...
}
How can I, using sed or another command line tool, switch around the returns and cases so it looks like this:
switch (argument0) {
case (0):
return "Goblin";
break;
case (1):
return "Fang";
break;
...
}
Something along the lines of
sed '/^[[:space:]]*case/ { N; s/case (\(.*\)):\(.* return \)\(.*\);/case (\3):\2\1;/; }' filename
That is:
/^[[: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;/
}
Note that this will only work for code that is formatted fairly strictly like the one you showed, with the return
directly in the line after the case
label and parentheses just the right way.
By the way, I can't think of a reason to have break;
directly after return
statements in C.
With GNU awk for multi-char RS:
$ 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;
...
}
Liberally sprinkle \\s*
s in the regexp if/when white space can occur.
sed '/^[[:space:]]*case/ {N;s/\(.*\)\("[^"]*"\)\(.*return \)\([^;]*\);/\1\4\3\2;/;}' YourFile
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.