3

How could I move files to subdirectories based on the common part of their names?

For example, with files named as comment_LastName.pdf and comment_LastName.md and sub-directories named as FirstName_LastName/ where all FirstName and LastName vary, how do I move files comment_X.pdf to subdirectory Mister_X/ ? (but for all files / directories at once)

Here's an unsuccessful attempt with zmv but I can't figure out the proper command...

zmv -n 'comment_(*).(pdf|md)' '*_$1/$f'

0

1 Answer 1

3

It looks like the destination operand for zmv gets quoted if you introduce any backreferences such as $1 and $f, so you can't add globbing in this case. The best option I found to solve this problem was to use the -p flag and give zmv a custom defined mv function.

This is what I came up with:

mv2 () { local dir dir=(*_$3:h) mv $1 $2 $dir[1]/$3:t } zmv -p mv2 'comment_(*).(pdf|md)' '$1/$f' 

In the mv2 function, we create an array of the directories you want to put the files in. Then in the actual mv command, we tag on the filenames to the directory array components. Globbing for the destination directories has to separated since these files don't exist yet. The globbing would fail otherwise.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.