将 C 代码中的左大括号移动到下一行?
Moving left brace in C code to the next line?
我有几个 C 源文件需要更改一个特定的格式设置功能。在文件的某些部分,
if (x == NULL) {
...
}
需要改为
if (x == NULL)
{
...
}
我希望使用 "indent" 命令,但它太激进了。它想用所有选项更改整个文件。
我想我可以在 Perl 或什至 Sed 中做到这一点,但我对两者都不太了解,无法弄清楚。
看来今天是我的幸运日,看来我想通了:
sed 's/^\([ ]*\)\(if (.* == NULL)\) {$/\n{/g' <filename>
有人可以确认这是正确的吗?
这有什么问题?
$ cat tst.c
#include "stdio.h"
int
main ()
{
void *x;
if (x == NULL) {
printf("darn\n");
}
return 0;
}
.
$ indent -i 4 -bli 0 -npcs -st tst.c
#include "stdio.h"
int
main()
{
void *x;
if (x == NULL)
{
printf("darn\n");
}
return 0;
}
如果您有其他不应更改的代码段示例,请创建一个包含这些代码段的示例程序并调整 indent
选项,直到您满意它输出的代码样式是你想要的风格。
在评论 中,indent
并不总是正确处理混淆代码,并给出了 prin\<newline>tf("...")
的示例。我不知道其他情况,但您可以在 sed 和 gcc 的帮助下通过 pre-processing 处理该情况:
$ cat tst.c
#include "stdio.h"
int
main ()
{
void *x;
// here is a comment
if (x == NULL) {
prin\
tf("darn\n");
}
return 0;
}
.
$ indent -i 4 -bli 0 -npcs -st tst.c
#include "stdio.h"
int
main()
{
void *x;
// here is a comment
if (x == NULL)
{
prin tf("darn\n");
}
return 0;
}
.
$ sed 's/a/aA/g;s/__/aB/g;s/#/aC/g' tst.c |
gcc -CC -P -traditional-cpp -E - |
sed 's/aC/#/g;s/aB/__/g;s/aA/a/g'
#include "stdio.h"
int
main ()
{
void *x;
// here is a comment
if (x == NULL) {
printf("darn\n");
}
return 0;
}
.
$ sed 's/a/aA/g;s/__/aB/g;s/#/aC/g' tst.c |
gcc -CC -P -traditional-cpp -E - |
sed 's/aC/#/g;s/aB/__/g;s/aA/a/g' |
indent -i 4 -bli 0 -npcs -st
#include "stdio.h"
int
main()
{
void *x;
// here is a comment
if (x == NULL)
{
printf("darn\n");
}
return 0;
}
我有几个 C 源文件需要更改一个特定的格式设置功能。在文件的某些部分,
if (x == NULL) {
...
}
需要改为
if (x == NULL)
{
...
}
我希望使用 "indent" 命令,但它太激进了。它想用所有选项更改整个文件。
我想我可以在 Perl 或什至 Sed 中做到这一点,但我对两者都不太了解,无法弄清楚。
看来今天是我的幸运日,看来我想通了:
sed 's/^\([ ]*\)\(if (.* == NULL)\) {$/\n{/g' <filename>
有人可以确认这是正确的吗?
这有什么问题?
$ cat tst.c
#include "stdio.h"
int
main ()
{
void *x;
if (x == NULL) {
printf("darn\n");
}
return 0;
}
.
$ indent -i 4 -bli 0 -npcs -st tst.c
#include "stdio.h"
int
main()
{
void *x;
if (x == NULL)
{
printf("darn\n");
}
return 0;
}
如果您有其他不应更改的代码段示例,请创建一个包含这些代码段的示例程序并调整 indent
选项,直到您满意它输出的代码样式是你想要的风格。
在评论 indent
并不总是正确处理混淆代码,并给出了 prin\<newline>tf("...")
的示例。我不知道其他情况,但您可以在 sed 和 gcc 的帮助下通过 pre-processing 处理该情况:
$ cat tst.c
#include "stdio.h"
int
main ()
{
void *x;
// here is a comment
if (x == NULL) {
prin\
tf("darn\n");
}
return 0;
}
.
$ indent -i 4 -bli 0 -npcs -st tst.c
#include "stdio.h"
int
main()
{
void *x;
// here is a comment
if (x == NULL)
{
prin tf("darn\n");
}
return 0;
}
.
$ sed 's/a/aA/g;s/__/aB/g;s/#/aC/g' tst.c |
gcc -CC -P -traditional-cpp -E - |
sed 's/aC/#/g;s/aB/__/g;s/aA/a/g'
#include "stdio.h"
int
main ()
{
void *x;
// here is a comment
if (x == NULL) {
printf("darn\n");
}
return 0;
}
.
$ sed 's/a/aA/g;s/__/aB/g;s/#/aC/g' tst.c |
gcc -CC -P -traditional-cpp -E - |
sed 's/aC/#/g;s/aB/__/g;s/aA/a/g' |
indent -i 4 -bli 0 -npcs -st
#include "stdio.h"
int
main()
{
void *x;
// here is a comment
if (x == NULL)
{
printf("darn\n");
}
return 0;
}