Reputation: 181
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;
...
}
Upvotes: 0
Views: 202
Reputation: 10039
sed '/^[[:space:]]*case/ {N;s/\(.*\)\("[^"]*"\)\(.*return \)\([^;]*\);/\1\4\3\2;/;}' YourFile
Upvotes: 0
Reputation: 44023
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.
Upvotes: 2
Reputation: 203229
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.
Upvotes: 2