how perform grep operation on all files in a directory

后端 未结 5 1777
情书的邮戳
情书的邮戳 2020-12-02 04:21

Working with xenserver, and I want to perform a command on each file that is in a directory, grepping some stuff out of the output of the command and appending it in a file.

相关标签:
5条回答
  • 2020-12-02 05:02

    grep $PATTERN * would be sufficient. By default, grep would skip all subdirectories. However, if you want to grep through them, grep -r $PATTERN * is the case.

    0 讨论(0)
  • 2020-12-02 05:06

    In Linux, I normally use this command to recursively grep for a particular text within a dir

    grep -rni "string" *
    

    where,

    r = recursive i.e, search subdirectories within the current directory
    n = to print the line numbers to stdout
    i = case insensitive search

    0 讨论(0)
  • 2020-12-02 05:10

    Use find. Seriously, it is the best way because then you can really see what files it's operating on:

    find . -name "*.sql" -exec grep -H "slow" {} \;
    

    Note, the -H is mac-specific, it shows the filename in the results.

    0 讨论(0)
  • 2020-12-02 05:16

    To search in all sub-directories, but only in specific file types, use grep with --include.

    For example, searching recursively in current directory, for text in *.yml and *.yaml :

    grep "text to search" -r . --include=*.{yml,yaml}
    
    0 讨论(0)
  • 2020-12-02 05:18

    If you want to do multiple commands, you could use:

    for I in `ls *.sql`
    do
        grep "foo" $I >> foo.log
        grep "bar" $I >> bar.log
    done
    
    0 讨论(0)
提交回复
热议问题