Ubuntu: Piping and File Manipulation

A little case scenario:

I used Rhythmbox to copy some songs to my cell phone’s memory card, and I had a nasty surprise: they all got separated into various directories, and I dislike that.

I didn’t want to manually move each file… So, instead of spending a few minutes doing just that, I spent a couple of hours finding out what piping is and stuff like that.

Most examples are very unrealistic. (“Let’s imagine we have file1, we move it to dir1…”) So I’ll use my particular case as an example.

Okay so I had all my MP3s deep into two directories each: Author / Album / Song

As some of the songs had incorrect or no information, most directories had one or two songs each. It was chaotic to find a song!

Important: If you don’t know what piping is, read this great visual explanation.

We can do this in the Terminal, from the directory that has all our subdirectories/MP3s:

find . -name "*.mp3" | while read n; do cp "$n" /new/path/; done

In the first part, we find all the MP3 files in the current directory (the dot) and its subdirectories. Then, we read its output, line by line. Each line is saved in a variable called n. As each line is, in fact, a file with its complete path, we simply use it as the source argument for the cp command.

Note: I encapsulated “$n” in quotes, otherwise, files with spaces will throw errors.

Note 2: You can replace the copy command (cp) with the move command (mv).

That way, all files are copied into one directory. ;-)


Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: