Shell编程文件搜索和追加

时间:2012-10-05 05:21:07

标签: shell search

我正在尝试编写一个shell程序,它将搜索我当前的目录(例如,我的包含C代码的文件夹),读取关键字“printf”或“fprintf”的所有文件,并将include语句附加到文件中它还没有完成。

我已经尝试编写搜索部分(目前,它所做的只是搜索文件并打印匹配文件列表),但它无法正常工作。下面是我的代码。我做错了什么?

Code

编辑:新代码。

#!/bin/sh
#processes files ending in .c and appends statements if necessary

#search for files that meet criteria
for file in $( find . -type f )
do
    echo $file
    if grep -q printf "$file"
    then
        echo "File $file contains command"
    fi
done

2 个答案:

答案 0 :(得分:0)

要在子shell中执行命令,您需要$( command )。请注意括号前的$

您不需要将文件列表存储在临时变量中,您可以直接使用

for file in $( find . ) ; do
    echo "$file"
done

并且

find . -type f | grep somestring

搜索文件内容但文件名称(在我的示例中所有文件名称 >包含“somestring”)

要grep文件的内容:

for file in $( find . -type f ) ; do
  if  grep -q printf "$file" ; then
    echo "File $file contains printf"
  fi
done

请注意,如果您匹配printf,它也会匹配fprintf(因为它包含printf

如果您只想搜索以.c结尾的文件,可以使用-name选项

find . -name "*.c" -type f

使用-type f选项仅列出文件。

在任何情况下,请检查您的grep是否有-r选项以递归方式搜索

grep -r --include "*.c" printf .

答案 1 :(得分:0)

你可以用sed -i做这件事,但我觉得这很令人反感。相反,对于流使用edseded似乎是合理的,因此当您不使用流时使用ed是有意义的。 / p>

#!/bin/sh

for i in *.c; do
    grep -Fq '#include <stdio.h>' $i && continue
    grep -Fq printf $i && ed -s $i << EOF > /dev/null
1
i
#include <stdio.h>
.
w
EOF
done