Saturday, January 14, 2017

command line - How to mass prepend text to file names?


Lets say I have a directory full of .md files all named various things. Lets say I wanted to prepend "text" to the front of each file name. So for example: file a.md, b.md, and c.md would become test - a.md, test - b.md, and test - c.md.


How would I accomplish this via command line?


Answer



One-liner that can be easily typed straight from the terminal:


for f in *.md; do mv "$f" "test - $f"; done

Or rewritten on separate lines instead using semicolons:


for f in *.md
do
mv "$f" "test - $f"
done

Exposition


Syntax of for (in sh):


for NAME [in WORDS ... ] ; do COMMANDS; done

Here, our NAME is f and our WORDS are all files in the current directory matching *.md. So the variable $f will be be substituted with each file matching *.md.


So for a.md:


mv "$f" "test - $f"

becomes


mv "a.md" "test - a.md"

The quotes are important because the each filename $f might contain spaces. Otherwise mv would think each word was a separate file. For example, if there were no quotes, and there's a file called Foo Bar.md, it would translate as:


mv Foo Bar.md test - Foo Bar.md

which would not work as intented. But by wrapping $f in quotes, it makes sense:


mv "Foo Bar.md" "test - Foo Bar.md"

Noting the syntax of for, you could also rename a subset of all the *.md files by naming each explicitly:


for f in a.md b.md d.md; do mv "$f" "Test - $f"; done

Or using shell expansion:


for f in {a,b,d}.md; do mv "$f" "Test - $f"; done

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...