Tuesday, December 1, 2015

Finding files with BASH and excluding some from the list.

I wanted to copy some files from the current directory to another based on file type, and file name. Bash 4.0 has some great things, such as globs:
shopt -s globstar nullglob extglob
I do not have Bash 4.0; I have Bash 3.2. So how does one list all files of a type, and then exclude some. The fastest way I found was to not use any external tools, but use case statements:
for f in *; do
  case "$f" in
     *.c |*.h | *.data| *.sh | Makefile) 
     # it's a valid filetype
          case "$f" in
          exportcode.sh | r.sh | project.report.sh)
          #exclude list is above
             ;;
          *)
             echo $f  # output the file name
             ;;
          esac   
         ;;
         *)
  # it's not
  ;;
   esac
done
The above code finds every file in the directory that is a .c .h .data .sh or Makefile and then excludes the file exportcode.sh, r.sh and project.report.sh. The resulting files are output via the "echo $f".

No comments:

Post a Comment