Madza Farias-Virgens
Madza Farias-Virgens

Reputation: 1061

Grep part of a file name and output to a .txt

I'm trying to grep pattern (the first 8 characters) for all files names in a directory and output to a .txt using this but it's not working. Why is that?

find . -type f -print | grep "^........" > test.txt

it still outputs the whole file name to the .txt

Upvotes: 0

Views: 243

Answers (2)

user9549915
user9549915

Reputation:

You're passing the output of the find command to grep, rather than passing the output as a list of files for grep to search. You can fix it with xargs like this:

find . -type f -print | xargs grep "^........" > test.txt

Upvotes: 1

Hunter McMillen
Hunter McMillen

Reputation: 61512

No need to use to grep at all, you can use the cut command to get the first 1-N characters without pattern matching:

find . -type f -print | cut -c1-8 > test.txt

Upvotes: 1

Related Questions