[英]Moving left brace in C code to the next line?
我有幾個C源文件需要更改一個特定的格式化功能。 在文件的某些部分,
if (x == NULL) {
...
}
需要改為
if (x == NULL)
{
...
}
我希望使用“縮進”命令,但它過於激進了。 它想要用所有選項更改整個文件。
我想我可以用Perl或者甚至Sed來做這個,但我不知道要么弄清楚這一點。
這有什么問題?
$ 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
選項,直到您對它輸出的代碼樣式是您想要的樣式感到高興。
@melpomene在評論中提到 indent
並不總是正確處理混淆代碼並給出了prin\\<newline>tf("...")
的示例。 關於其他案例的idk但你可以通過在sed和gcc的幫助下進行預處理來處理那個案例:
$ 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;
}
看起來今天是我的幸運日,因為看起來我想通了:
sed 's/^\([ ]*\)\(if (.* == NULL)\) {$/\1\2\n\1{/g' <filename>
有人可以確認這是正確的嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.