Using find command in bash script

后端 未结 3 1646
旧巷少年郎
旧巷少年郎 2021-01-30 09:39

I just start to use bash script and i need to use find command with more than one file type.

list=$(find /home/user/Desktop -name \'*.pdf\') 

t

相关标签:
3条回答
  • 2021-01-30 09:49

    If you want to loop over what you "find", you should use this:

    find . -type f -name '*.*' -print0 | while IFS= read -r -d '' file; do
        printf '%s\n' "$file"
    done
    

    Source: https://askubuntu.com/questions/343727/filenames-with-spaces-breaking-for-loop-find-command

    0 讨论(0)
  • 2021-01-30 09:55

    Welcome to bash. It's an old, dark and mysterious thing, capable of great magic. :-)

    The option you're asking about is for the find command though, not for bash. From your command line, you can man find to see the options.

    The one you're looking for is -o for "or":

      list="$(find /home/user/Desktop -name '*.bmp' -o -name '*.txt')"
    

    That said ... Don't do this. Storage like this may work for simple filenames, but as soon as you have to deal with special characters, like spaces and newlines, all bets are off. See ParsingLs for details.

    $ touch 'one.txt' 'two three.txt' 'foo.bmp'
    $ list="$(find . -name \*.txt -o -name \*.bmp -type f)"
    $ for file in $list; do if [ ! -f "$file" ]; then echo "MISSING: $file"; fi; done
    MISSING: ./two
    MISSING: three.txt
    

    Pathname expansion (globbing) provides a much better/safer way to keep track of files. Then you can also use bash arrays:

    $ a=( *.txt *.bmp )
    $ declare -p a
    declare -a a=([0]="one.txt" [1]="two three.txt" [2]="foo.bmp")
    $ for file in "${a[@]}"; do ls -l "$file"; done
    -rw-r--r--  1 ghoti  staff  0 24 May 16:27 one.txt
    -rw-r--r--  1 ghoti  staff  0 24 May 16:27 two three.txt
    -rw-r--r--  1 ghoti  staff  0 24 May 16:27 foo.bmp
    

    The Bash FAQ has lots of other excellent tips about programming in bash.

    0 讨论(0)
  • 2021-01-30 09:57

    You can use this:

    list=$(find /home/user/Desktop -name '*.pdf' -o -name '*.txt' -o -name '*.bmp')
    

    Besides, you might want to use -iname instead of -name to catch files with ".PDF" (upper-case) extension as well.

    0 讨论(0)
提交回复
热议问题