Search code examples
macoszshoh-my-zsh

Moving files according to some pattern with Zsh on MacOS


I'm trying to move files according to some pattern, in the case below, moving all files containing 2018 to 2018/ folder:

mv *2018* 2018/

This command worked once with 2017, now then I'm getting

mv: rename 2018 to 2018/2018: Invalid argument

So I tried zmv:

autoload -Uz zmv
mv *2018* 2018/

It worked, but doesn't work anymore for 2019 or any other value with the same error message.

How should I fix it ? Or what is a better and yet simple way to move files according to some regex pattern ?

I also have oh-my-zsh installed


Solution

  • Try this:

    mv *2018*(.) 2018/
    

    With the . glob qualifier (in the parentheses), the wildcard pattern will only match regular files. Without the qualifier, the source pattern will include the destination directory 2018 in the list of items to move, and mv cannot move a directory into itself.

    When I tried the original pattern *2018* on my system, mv still moved the matching files as requested, and then reported the error message about the directory. I suspect that when this appeared to work, the error message was simply lost in some other text.

    Demonstrating the . glob qualifier:

    >>>> ls -p1
    2017/
    2017a.txt
    2017b.txt
    2018/
    2018a.txt
    2018b.txt
    2019/
    2019a.txt
    2019b.txt
    >>>> print -l *2018*   
    2018
    2018a.txt
    2018b.txt
    >>>> print -l *2018*(.)
    2018a.txt
    2018b.txt
    >>>> mv *2018*(.) 2018/
    >>>> ls -pR1           
    2017/
    2017a.txt
    2017b.txt
    2018/
    2019/
    2019a.txt
    2019b.txt
    
    ./2017:
    
    ./2018:
    2018a.txt
    2018b.txt
    
    ./2019:
    

    BTW, the zmv example in your question is invoking mv, not zmv. Also, arguments to zmv usually need to be quoted. You don't want zmv here, mv will do everything needed.