自学内容网 自学内容网

【嵌入式开发 Linux 常用命令系列 7.7 -- find 和 sed 配合使用介绍】


请阅读嵌入式及芯片开发学必备专栏


使用背景

当时想在 linux 环境下 使用 find 命令找到 .c.h 文件,并使用xargssed 命令将文件中所有"demo" 字符串替换为 “hello”

命令实现

  1. 使用 find 命令查找 .c.h 文件
  2. 通过 xargs 将找到的文件列表传递给 sed 命令
  3. 使用 sed 命令在文件中替换字符串

具体命令:
以下是一个完整的命令行示例:

find . -type f \( -name "*.c" -o -name "*.h" \) -print0 | xargs -0 sed -i 's/demo/hello/g'

命令解释:

  1. find . -type f \( -name "*.c" -o -name "*.h" \)
    • find .:从当前目录开始查找。
    • -type f:只查找文件(不包含目录)。
    • \( -name "*.c" -o -name "*.h" \):查找扩展名为 .c.h 的文件。括号和 -o 用于指定多个条件。
  2. -print0
    • -print0:以 null 字符(\0)结尾的方式输出文件名。这是为了处理文件名中可能包含的空格或换行符。
  3. xargs -0
    • xargs -0:从标准输入读取以null字符结尾的输入,并将其传递给后续命令。在这里,它将文件列表传递给 sed 命令。
  4. sed -i 's/demo/hello/g'
    • sed:流编辑器,用于文本处理。
    • -i:直接在文件中进行替换(而不是输出到标准输出)。
    • 's/demo/hello/g':表示全局替换所有匹配的 demo 字符串为 hello

注意事项

  • 使用 -print0xargs -0 是为了确保文件名中包含空格或特殊字符时能够正确处理。
  • sed -i 直接修改文件,请确保在执行命令前备份文件,以防止意外的数据丢失。

使用示例

假设当前目录下有如下文件:

file1.c
file2.h
subdir/file3.c
subdir/file4.h

这些文件中包含以下内容:

// file1.c
int main() {
    printf("This is a demo.\n");
    return 0;
}
// file2.h
#define DEMO_CONSTANT 10
// subdir/file3.c
int demoFunction() {
    return 0;
}
// subdir/file4.h
#ifndef DEMO_H
#define DEMO_H
#endif

执行上述命令后,文件内容将被修改为:

// file1.c
int main() {
    printf("This is a hello.\n");
    return 0;
}
// file2.h
#define DEMO_CONSTANT 10
// subdir/file3.c
int helloFunction() {
    return 0;
}
// subdir/file4.h
#ifndef HELLO_H
#define HELLO_H
#endif

如上所示,所有 .c.h 文件中出现的 demo 字符串都被替换为了 hello


原文地址:https://blog.csdn.net/sinat_32960911/article/details/140673787

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!