Bash:如何转换此文本以满足我的需求



我正在编写一个 Bash 脚本,我需要在其中转换一堆如下所示的行:

/* 100 */ "Continue",
/* 101 */ "Switching Protocols",
# ...

对此:

case 100: return "Continue";
case 101: return "Switching Protocols";
# ...

如何使用命令行工具执行此操作?我问的原因是因为我不确定如何使用正则表达式 + sed/grep "捕获"变量(100,"继续"(并将它们转换为新的文本行。

如果您有兴趣,这里是完整输出的要点(请注意,有些行末尾没有逗号(: https://gist.github.com/aa5d19778844334b3ecd7d98cca67301

谢谢!

编辑者@EdMorton

链接文件中显示的实际 4 种不同输入样式以及一种不存在但可能发生的输入样式是:

/* 101 */ "Switching Protocols",
/* 425 */ null,
/* 426 */ "Upgrade Required", // RFC 2817
/* 507 */ "Insufficient Storage"
/* 999 */ "Made Up But Could Happen" // RFC 9999

请为上述所有内容提供以下预期输出:

case 101: return "Switching Protocols";
case 425: ?
case 426: ?
case 507: return "Insufficient Storage";
case 999: ?

如果你可以在末尾有C风格的注释,例如 /* 426 */ "Upgrade Required", /* RFC 2817 */,然后包括案例来涵盖这一点。

你可以

用简单的sed替换和GNU sed来做到这一点,比如:

sed -r 's+/*+case+g; s+s**/s*+: return +g; s+(,s*)?(//.*)?$+;2+g' yourfile

sed s命令使用 + 作为分隔符(通常使用/,但注释也/(。*需要逃脱并变得*

有趣的s**/s*意味着:可选的空格s*后跟一个星星(转义后变为*(,后跟/,然后是可选的空格s*

使用 sed:

sed 's%/* ([0-9]*) */ ([^,]*).*%case 1: return 2;%'
$ sed -r 's/[^0-9]+([0-9]+).*(".*").*/case 1: return 2;/' file
case 100: return "Continue";
case 101: return "Switching Protocols";

假设这是 switch 语句的块,这将适用于更新的输入样式。

$ sed -r 's_/*_case_;s_ */_: return_;s_("[^"]*")[^;]?_1;_;s_,$_;_' file          
case 101: return "Switching Protocols";
case 425: return null;
case 426: return "Upgrade Required"; // RFC 2817
case 507: return "Insufficient Storage";
case 999: return "Made Up But Could Happen";// RFC 9999

还处理末尾缺少的逗号。 显然,如果 null 不是可接受的值,则必须将其替换为默认值。

最新更新