【问题标题】:Finding files by extension in a folder and displaying their contents在文件夹中按扩展名查找文件并显示其内容
【发布时间】:2018-03-21 16:06:44
【问题描述】:

我需要做的是在一个文件夹及其子文件夹中找到所有的 c 文件(.c 文件扩展名)。它还需要打印每个 c 文件的函数名(不是全部内容)。

到目前为止我所做的是:

find "$1" -type f -name *.c -exec echo {}":" \; -exec grep -i "(*)" {} \;

但问题是,它应该是这样打印的:

fs/folder/a.c:
int test_function()

fs/project_1/src/b.c:
void test_function_1(int loc)
int test_function_2(int loc)

fs/project_1/util/c.c:
FILE* test_function_3(char* name)
void test_function_4(FILE* file)
void test_function_5(FILE* file)

但是我上面写的shell脚本是这样打印出来的:

fs/folder/a.c:
int test_function() {
fs/project_1/src/b.c:
void test_function_1(int loc) {
int test_function_2(int loc) {
fs/project_1/util/c.c:
FILE* test_function_3(char* name) {
void test_function_4(FILE* file) {
void test_function_5(FILE* file) {

1) 有没有办法删除那些“{”正则表达式并在每个文件之间添加新行?

2) 另外,当我执行程序时,作为输出打印的文件的顺序总是不同的。可以排序吗? (当我尝试 -exec sort {} \ 时,这会使输出完全错误......)

3)最后,我怎样才能让它在输入(文件夹名称)时出现错误消息 是不是文件夹? (eg) 执行时./findfn.sh abcd

有人可以帮我解决这个问题吗?我被这个问题困扰了好几个小时......如果有人打破我的困惑,我将非常感激......谢谢!

【问题讨论】:

    标签: regex shell find


    【解决方案1】:

    您可以使用printf

    find "$1" -type f -name '*.c' -exec printf '\n%s:\n' {} \; -exec grep -i "(.*)" {} \;
    

    但是,这种方法会更有效,因为它避免了为每个文件创建一个子 shell:

    while IFS= read -rd '' file; do
       printf '%s:\n' "$file"
       if grep -c '(.*)' "$file"; then
          grep "(.*)" "$file" | sed 's/{//g'
       else 
           echo 'no functions'
       fi
       echo
    done < <(find "$1" -type f -name '*.c' -print0)
    

    【讨论】:

    • 对不起,我昨天睡了……快到了!!我只需要在 funtion_names() 之后删除 { 但是 | sed 's/{//g' |在这里不起作用...我应该如何删除 {??
    • 另外,如果我使用您编写的上述脚本,那么第一行也会有一个新行,还有我必须删除的“{”...
    • 是的,不用担心,我刚刚想通了,但是如果文件夹中的 c 文件在其内容中不包含任何功能,我会出错吗?
    • 有什么办法可以打印“无功能”之类的东西而不是什么都不打印?
    • 谢谢阿努巴瓦!将等待您的回复!
    猜你喜欢
    • 1970-01-01
    • 2013-04-12
    • 2011-03-10
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    • 2023-04-07
    • 1970-01-01
    • 2017-11-25
    相关资源
    最近更新 更多