Renaming every file in a directory with zsh is a common scenario when you're working with a series of related files. Using zsh's "for" loop, you can access the name of every file. Then using zsh's string replacement syntax of ${name/replace/with) you can...
Duration
2 min
Access
Free
Transcript
Available
Renaming every file in a directory with zsh is a common scenario when you're working with a series of related files. Using zsh's "for" loop, you can access the name of every file. Then using zsh's string replacement syntax of ${name/replace/with) you can adjust the file names.
Video Transcript
John Lindquist: In this processed directory, I have a bunch of files which accidentally have -processed.m4v attached to the end of them. To test out renaming something, let's set a name equal to one of the files in the directory. I'll type 001. Hit Tab, which will select the file that starts with 001.
Now if I echo name, you'll see it outputs the name of that file. My goal is to replace this with nothing, essentially just removing it. If I echo, say dollar, then curly braces, and then write name/, the thing I want to replace, so a -processed, and then another slash. I'll hit Enter. You'll see we got rid of -processed, and we still have m4v there.
I'll hit up and try this again. Let's try m4v. Hit Enter. You'll see this is the name that we want. Now, to loop through every file in the directory, I'll say for file in the current directory and just put an asterisk. Hit Enter, and this brings up a for> prompt. In this for> prompt, I can just echo, right now, the file name. This should echo out every single file just to show that working.
Now, I'll clear that with Command-K. If I type that for loop again, for file in the current directory, get every file go back into the prompt, we'll just type mv, which is the command to rename files. I can type in the $file, which gives us the original file name.
Then I can type dollar, curly braces, file, what I want to remove, -processed.m4v, and then another slash. I'm going to leave this empty because I just want to remove it. I don't want to replace it with anything. We'll hit enter here. When I look in my processed directory, you'll see everything is renamed and -processed.m4v is removed from every file name.