You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Coccinelle查找并移除带冗余换行符的LOG宏调用

用Coccinelle清理LOG宏中冗余的末尾换行符

编写Coccinelle规则脚本

创建一个名为remove_log_trailing_n.cocci的脚本,内容如下:

// 处理带可变参数的LOG调用:匹配格式字符串末尾带"\n"的情况
@format_call@
expression args;
string fmt_str;
@@
- LOG(fmt_str"\n", args)
+ LOG(fmt_str, args)

// 处理无参数的纯字符串LOG调用:匹配字符串常量末尾带"\n"的情况
@literal_call@
string plain_str;
@@
- LOG(plain_str"\n")
+ LOG(plain_str)

规则说明

  • @format_call@:针对带格式参数的LOG调用(比如LOG("count: %d\n", total)),识别格式字符串末尾的"\n",将其移除后保留原参数列表。
  • @literal_call@:针对仅传入单个字符串常量的LOG调用(比如LOG("operation done\n")),直接去掉字符串末尾的"\n"。

执行脚本清理代码

在代码目录下运行Coccinelle的spatch命令处理目标文件:

# 处理单个文件
spatch --sp-file remove_log_trailing_n.cocci target_code.c

# 批量处理目录下所有C文件
spatch --sp-file remove_log_trailing_n.cocci *.c

注意事项

  • 脚本会自动识别C语言的字符串拼接(比如LOG("hello " "world\n")),正确移除末尾的冗余换行符。
  • 仅会移除格式字符串末尾的\n,不会影响字符串中间的换行符(比如LOG("line1\nline2\n")会被修正为LOG("line1\nline2"))。

内容的提问来源于stack exchange,提问作者Yasushi Shoji

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 03:07:37