Moving multiple files having spaces in name (Linux)

前端 未结 3 971
囚心锁ツ
囚心锁ツ 2020-12-04 03:13

I have a directory which contains multiple files with spaces in their names. I want to find a pattern in the name and those file will be moved to some other directory. Now t

相关标签:
3条回答
  • 2020-12-04 03:21

    No need to use a loop:

    find . -maxdepth 1 -name "*$pattern*xlsx" -type f -exec mv {} $destination +
    
    0 讨论(0)
  • 2020-12-04 03:40

    Sometimes, the logic to insert in the body of the loop could be complex enough to warrant an actual bash loop.

    Here is a solution that works that way:

    find . -maxdepth 1 -name "*$pattern*xlsx" -type f | while IFS= read -r file
    do
       mv "$file" $destination/
    done
    

    Edit: kudos to @KamilCuk for the IFS=, to handle filenames with leading and trailing whitespace, and -r, to handle filenames with escaped backspace characters.

    Known limitation: this solution will not work for filenames that have embedded newlines. For such cases, see the other answers to this question.

    Solution from @Charles Duffy in comments to Moving files with whitespace what will work even with newlines in the file names:

    • add -print0 to the find command to terminate records with the NULL character
    • add -d '' to the read command to read records terminated by NULL
    find . -maxdepth 1 -name "*$pattern*xlsx" -type f -print0 | while IFS= read -r -d '' file
    do
       mv "$file" $destination/
    done
    
    0 讨论(0)
  • 2020-12-04 03:42

    Working fine with following code

    find . -maxdepth 1 -name "*$pattern*xlsx" -type f -print0 | xargs -I{} -0 mv {} "$destination/"
    
    0 讨论(0)
提交回复
热议问题