2

I have quite a few files with different extensions sitting under sub folders like 'aaa'

/f1/aaa/a.txt
/f1/aaa/a.sql
/f1/f2/aaa/b.txt
/f1/f2/aaa/b.csv

what I need is to extract all these files from /f1 and only remove their extensions:

/f1/aaa/a
/f1/f2/aaa/b
2
  • 1
    find ./ -type f | grep -i aaa | while read fn; do echo ${fn%.*};done
    – zinking
    Nov 4, 2013 at 2:54
  • Are you intending to actually move the files, just display their names, or remove the file extensions from the actual file? In the first or last case, you will end up losing some files. Nov 4, 2013 at 6:34

1 Answer 1

1

If by "extract and remove their extensions" you mean renaming them as you go, this would achieve it.

find f1 -path "*/aaa/*" -type f -exec bash -c 'mv -i -- "$0" "${0%.*}"' {} \;

Or, to merely print the files without their extension:

find f1 -path "*/aaa/*" -type f -exec bash -c 'echo "${0%.*}"' {} \;

Instead of greping over find's output, you should use its built-in filtering capabilities to find the matching files. Otherwise, you'd get false positives for files including the string aaa.

Filename substitutions should always be quoted to prevent whitespace or shell glob patterns from being expanded.

Furthermore, find output shouldn't be piped to while unless you null-delimit the output. If you really just want to "do something" with every file, piping to while is not necessary. The same effect can be achieved with the -exec option.

If you need find … | while, then this is safer (don't forget to quote the filename):

find … -print0 | while IFS= read -r -d '' file; do command "$file"; done

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .