赞
踩
当时想在 linux
环境下 使用 find
命令找到 .c
和 .h
文件,并使用xargs
加 sed
命令将文件中所有"demo" 字符串替换为 “hello”
命令实现:
find
命令查找 .c
和 .h
文件。xargs
将找到的文件列表传递给 sed
命令。sed
命令在文件中替换字符串。具体命令:
以下是一个完整的命令行示例:
find . -type f \( -name "*.c" -o -name "*.h" \) -print0 | xargs -0 sed -i 's/demo/hello/g'
命令解释:
find . -type f \( -name "*.c" -o -name "*.h" \)
:
find .
:从当前目录开始查找。-type f
:只查找文件(不包含目录)。\( -name "*.c" -o -name "*.h" \)
:查找扩展名为 .c
或 .h
的文件。括号和 -o
用于指定多个条件。-print0
:
-print0
:以 null 字符(\0)结尾的方式输出文件名。这是为了处理文件名中可能包含的空格或换行符。xargs -0
:
xargs -0
:从标准输入读取以null字符结尾的输入,并将其传递给后续命令。在这里,它将文件列表传递给 sed
命令。sed -i 's/demo/hello/g'
:
sed
:流编辑器,用于文本处理。-i
:直接在文件中进行替换(而不是输出到标准输出)。's/demo/hello/g'
:表示全局替换所有匹配的 demo
字符串为 hello
。-print0
和 xargs -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
。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。