How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?

前端 未结 11 1697
梦如初夏
梦如初夏 2020-11-22 13:50

Say I want to copy the contents of a directory excluding files and folders whose names contain the word \'Music\'.

cp [exclude-matches] *Music* /target_direc         


        
11条回答
  •  余生分开走
    2020-11-22 14:07

    My personal preference is to use grep and the while command. This allows one to write powerful yet readable scripts ensuring that you end up doing exactly what you want. Plus by using an echo command you can perform a dry run before carrying out the actual operation. For example:

    ls | grep -v "Music" | while read filename
    do
    echo $filename
    done
    

    will print out the files that you will end up copying. If the list is correct the next step is to simply replace the echo command with the copy command as follows:

    ls | grep -v "Music" | while read filename
    do
    cp "$filename" /target_directory
    done
    

提交回复
热议问题