Geek Grid
Geek Grid

Reputation: 207

BASH How to loop through directories and extract filenames

If I have the following folder structure, how would I loop through each directory, extract the file names in each directory, and get the first bit of text in the array?

Folder1
    File1-test
    File2-test
Folder2
   File3-test
   File4-test

I need File1, File2, File3 etc.

Upvotes: 0

Views: 180

Answers (1)

jayant
jayant

Reputation: 2389

find . -type f -name "*-test" | awk -F/ '{print $NF}' | sed 's/-test//'

Look for all files match *-test pattern, then split path using / and print only the last field, then remove the -test part.

Alternative method

find . -type f -name "*-test" | awk -F/ '{print $NF}' | awk -F- '{print $1}'

Upvotes: 1

Related Questions