1

I have a directory tree where some of the directories have spaces in the names:

top
|-- subdir 1
    |-- subdir a
        |-- file1.csv
        |-- file2.csv
    |-- subdir b
        |-- file1.csv
    |-- subdir c
        |-- file3.csv

I want to write a grep command to recursively find text in the directory structure, but the output has to be sorted according to the timestamp of the files. The closes I've gotten is this:

find . -name *.csv | sort | xargs grep "some text" -0

The problem is that the spaces are throwing off grep and you get results like

grep: ./subdir: No such file or directory
grep: 1: No such file or directory

It's interpreting subdir 1 as two separate directories, subdir and 1. How can I do this?

1 Answers1

1

Yes, these spaces are the problem. If the tools you use can work with null-terminated strings, this is the way:

find . -name "*.csv" -print0 | sort -z | xargs -0 grep "some text"

This approach should also work in your case:

find . -name "*.csv" | sort | xargs -I {} grep "some text" {}

Notes:

  • I don't know how this sort makes "the output sorted according to the timestamp of the files". I'm just debugging your command.
  • You need to quote *.csv like I did to avoid this scenario.