Home > Mobile >  write list of all the files in a directory and subdirectory except 1 in linux
write list of all the files in a directory and subdirectory except 1 in linux

Time:03-11

Suppose I have 2 directories src/A, src/B and src/C.

I want to list all the files inside A and B but not C.

This working fine but it's also listing file of src/C

find src/ -type f >> changed-files-list.txt

I tried

find src/ -type f -not -name 'src/C' >> changed-files-list.txt

but it's not working I guess because I used -type f. How can exclude a directory from above command?

CodePudding user response:

Try:

shopt -s extglob dotglob
find src/!(C) -type f >> changed-files-list.txt
  • The extglob option with shopt -s turns on Bash extended globbing. See extglob in glob - Greg's Wiki. It causes src/!(C) to expand to the same list as src/*, but excluding src/C.
  • The dotglob option with shopt -s causes glob patterns to match files or directories whose names start with a dot (.). It means that src/!(C) will match src/.D, for instance.

CodePudding user response:

Suggesting to use ls command

ls -1 src/{A,B}/*

Option -1 list one file per line (like find).

Advantage list only the specified directories. And not traversing under.

CodePudding user response:

Use -prune to omit the directory:

find src -path src/C -prune -o \( -type f  -print \)

If you are willing to accept the line of output that includes C itself (but none of the files in C), you can simplify that to:

find src -name C -prune -o -type f

(this will also omit any files names C)

  • Related