r3dux.org

A number-pimping side project from the valleys in *NEW* upside-down flavour.

  • Home
  • ABOUT
  • OLD SITE
  • SEARCH
  • FEEDBACK

How-To: Replace characters in filenames in Linux

r3dux | September 18, 2011

Occassionally you’re likely to end up with a bunch of files with filenames that are underscore separated or space separated when you want them the other way around, and then you either have to manually rename them by hand, or live with it.

I had this issue the other day so I wrote a script to convert all filenames in the current directory to the specified format.

The script switches are:

  • -t – turns on [T]esting mode, which displays what would happen if you ran the script, but makes absolutely no changes to filenames.
  • -u – converts all [U]nderscores to spaces.
  • -s – converts all [S]paces to underscores.
  • -l – converts all filenames to [L]owercase.
  • -p – converts all filenames to u[P]percase.

It’d be nice if I could get all working recusively and offer an option to Capitalise Each Word in the filenames, but this will do for now.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# Script to replace characters in filenames | September 2011 | r3dux
# Note: This script will work on files in the present working directory only.
 
# Initiate counters
changeCount=0;
ignoreCount=0;
 
# Initiate flags
displayUsage="FALSE"
testRun="FALSE"
u2sMode="FALSE"
s2uMode="FALSE"
toLowercase="FALSE"
toUppercase="FALSE"
proceed="FALSE"
 
# Set flags from the user provided parameters
while getopts "htuslp" optname
do
	case "$optname" in
		"h")
			displayUsage="TRUE"
			;;
		"t")
			echo "Test mode only - no filenames will be modified..."
			testRun="TRUE"
			;;
		"u")
			echo "Mode set to convert underscores to spaces..."
			u2sMode="TRUE"
			proceed="TRUE"
		        ;;
	        "s")
			echo "Mode set to convert spaces to underscores..."
			s2uMode="TRUE"
			proceed="TRUE"
		        ;;
		"l")
			echo "Mode set to convert filenames to lowercase..."
			toLowercase="TRUE"
			;;
		"p")
			echo "Mode set to convert filenames to uppercase..."
			toUppercase="TRUE"
			;;
		# Catch-all for unknown switches
	        *)
			echo
			echo "Unknown error while processing parameters. Please use -h to display usage paramaters."
			echo
			exit 0
        		;;
	esac
done
echo
 
# If asked to, or if we got a parameter we don't recognise show the usage options
if [ $displayUsage == "TRUE" ]; then
	echo "repchars is a small script to replace characters in filenames, or vice versa."
	echo
	echo "Usage: repchars [-t] (-u | -s) [-l | -p]"
	echo
	echo -e "-t\tturns on [T]esting mode, which displays what would happen if you ran the script, but makes absolutely no changes to filenames."
	echo -e "-u\tconverts all [U]nderscores to spaces."
	echo -e "-s\tconverts all [S]paces to underscores."
	echo -e "-l\tconverts all filenames to [L]owercase."
	echo -e "-p\tconverts all filenames to u[P]percase."
	echo
	echo "You can use use any combination of parameters except the mutually exclusive options -u and -s, and -l and -p."
	echo
	echo "It's recommended that you do a trial run with the -t switch to be sure the outcome is as you want it before commiting!"
	echo
 
	exit 0;
fi
 
# Moan if we have both 'toLowercase' and 'toUppercase' set (mutually exclusive)
if [ $toUppercase == "TRUE" -a $toLowercase == "TRUE" ]; then
	echo "You cannot convert to both uppercase and lowercase at the same time."
	proceed="FALSE"
fi
 
# Moan if we have both 'spaces-to-underscores' and 'underscores-to-spaces' set (mutually exclusive)
if [ $s2uMode == "TRUE" -a $u2sMode == "TRUE" ]; then
	echo "You cannot convert spaces to underscores and underscores to spaces at the same time."
	proceed="FALSE"
fi
 
# If the proceed flag isn't set, we don't proceed...
if [ $proceed == "FALSE" ]; then
	echo "Please use repchars -h for usage instructions."
	echo
	exit 0;
fi
 
# Function to replace characters dependent on the flags set
function replaceChars()
{
	# Note: Once we're in this function $1 isn't the first parameter passed to the 
	# script, it's the first (and only) parameter passed to this function.
 
	# If appropriate, convert underscores to spaces
	if [ $u2sMode == "TRUE" ]; then
		newFilename=$(echo "$1" | tr _ ' ')
	fi
 
	# If appropriate, convert spaces to underscores
	if [ $s2uMode == "TRUE" ]; then
		newFilename=$(echo "$1" | tr ' ' _)
	fi
 
	# If apppropriate, convert filenames to lowercase
	if [ $toLowercase == "TRUE" ]; then
		newFilename=$(echo "$newFilename" | tr 'A-Z' 'a-z')
	fi
 
	# If apppropriate, convert filenames to uppercase
	if [ $toUppercase == "TRUE" ]; then
		newFilename=$(echo "$newFilename" | tr 'a-z' 'A-Z')
	fi
 
	# Only modify the filename if the original and new filenames are not the same thing
	# (i.e. there may be nothing to change, and if we mv the file to itself mv will complain)
	if [ "$1" != "$newFilename" ]; then
 
		let changeCount+=1
 
		if [ $testRun == "FALSE" ]; then
			echo "Original filename: $1"
			echo "New filename     : $newFilename"
			echo `mv "$1" "$newFilename"` # This actually renames the file
		else
			echo "*TESTRUN* Original filename: $1"
			echo "*TESTRUN* New filename     : $newFilename"
			echo
		fi
	else
		let ignoreCount+=1
 
		echo -e "No change required to filename: $1"
	fi
}
 
# Call the replacement function on each file
for f in *; do
 
	replaceChars "$f" 
 
done # End of file checking loop
 
# Finally, display the counts of filename changes and exit
echo
if [ $testRun == "TRUE" ]; then
	echo "We would have changed the filenames of $changeCount file(s) and ignored $ignoreCount file(s) which required no changing."
else
	echo "Changed the filenames of $changeCount file(s) and ignored $ignoreCount file(s) which required no changing."
fi
echo

Like most scripting, this entire thing could probably be done in a single line, but I found it useful to learn how to use getopts and such.

Hope someone else finds it useful! Oh, and if you need a do-everything file renaming script, I read that FixNames script does what it says on the tin.

Comments
No Comments »
Categories
How-To, Linux
Tags
Bash, getopts, Rename, script, Shell, Space, Underscore
Comments rss Comments rss
Trackback Trackback

How to: Get absolute/relative file paths, filenames and extensions from a Bash script

r3dux | June 16, 2011

I’ve been learning some Qt stuff today, and the resulting code requires pre-processing of header files to work correctly, which I thought I’d try to automate. As part of this, I needed to find out how to get at all the different elements of a file from a bash script, so I did some googling and got all the info I needed :)

The script itself isn’t particularly useful, but the component parts of how to get at paths, extensions, and plain filenames without extensions definitely is – check it out:

fileParts Shell Script

# Bash script to get filename details | 16-06-2011 | r3dux
# Usage: fileParts <extension-with-no-dot> i.e. fileParts cpp
 
# For each file with the given extension in the current directory...
for file in ./*.$1; do
 
	# If a file exists with a given extension...
	if [ -e "$file" ]; then
 
		fullPath=$(readlink -f "$file")
		echo "Full path and filename          is: " $fullPath
 
		echo "Relative path and filename      is: " $file
 
		fileWithoutPath=$(basename $file)
		echo "Filename only                   is: " $fileWithoutPath
 
		extension=${fileWithoutPath##*.}
		echo "File extension only             is: " $extension
 
		fileWithoutExtension=${fileWithoutPath%.*}
		echo "Filename only without extension is: " $fileWithoutExtension
 
		echo
	else
		echo "No files of type $1 found!"
		exit 0
 
	fi # End of if file exists condition				
 
done # End of for each file loop

I created two dummy “.h” files in my home folder and ran the script – this is what it outputs:

r3d2@r3dux-Aspire-8920:~$ ./fileParts h
Full path and filename          is:  /home/r3d2/a-simple-test-file.h
Relative path and filename      is:  ./a-simple-test-file.h
Filename only                   is:  a-simple-test-file.h
File extension only             is:  h
Filename only without extension is:  a-simple-test-file
 
Full path and filename          is:  /home/r3d2/file.with.lots.of.dots.h
Relative path and filename      is:  ./file.with.lots.of.dots.h
Filename only                   is:  file.with.lots.of.dots.h
File extension only             is:  h
Filename only without extension is:  file.with.lots.of.dots

That’s gotta come in useful, right? =D

Comments
No Comments »
Categories
Coding, How-To
Tags
Absolute, Bash, Extension, Filename, Path, Relative, script, Shell
Comments rss Comments rss
Trackback Trackback

How To: Remove all desktop.ini (or indeed any recurring) files in Linux

r3dux | January 29, 2011

I spent a while going through my music hive today, just putting music I’d ripped and dumped into the New folder into the correct spot, placing all albums by the same band into a folder called the band name etc, and there’s a hella lot of desktop.ini and Thumbs.db files floating around. This might be useful for people running Windows, but I’m not (or at least not anymore, and not for a long, long time) – so lets be rid of them, shall we?

Blatantly Unnecessary Warning: Deleting files deletes files! Fo’ real, yo! So try out the “tester” script before unconditionally deleting things you might now want to! =D

Measure Twice, Cut Once

Before we delete files en masse – let’s check to see what files we’re opting to remove. To do this, and assuming we want to check what desktop.ini files we can remove, just enter something along the lines of the following into the bash:

find path-to-folder -name desktop.ini

For example, if my music is stored on my NAS at /mnt/Share/_Serva, then to check what files will be removed, I’ll enter:

find /mnt/Share/_Serva -name desktop.ini

After hitting return on the above, you should be given a list of instances of files called desktop.ini and we get to put our minds at ease that it’s not even thinking about adding any other files (such as mp3s or what-have-you) to the list.

Cease and Desist

Once we’re happy we’re going to remove only the files we want gone, to interactively delete all the desktop.ini files from a given folder and any subfolders (and by interactively, I mean it’ll ask you whether you want to delete each one), enter the following command into the bash:

find path-to-folder -name desktop.ini -exec rm -i {} \;

So in my instance, to interactively (i.e. I’d then have to confirm each delete) remove all instances of desktop.ini, I’d enter:

find /mnt/Share/_Serva -name desktop.ini -exec rm -i {} \;

If I wanted to automatically remove all copies of files named desktop.ini without confirming each deletion, then I can just strip off the -i switch, leaving:

find path-to-folder -name desktop.ini -exec rm {} \;

You can then do the same thing for Thumbs.db or any other filename just by substituting the appropriate details after the -name switch.

Done & done =D

P.S. Just for the record, removing the -i will make the deletion occur automatically unless the file is write-protected, but you can always sudo that away, just like the request for a sandwich.

Credits & thanks: MegaJim over on Ubuntu Forums.

Comments
1 Comment »
Categories
Coding, Linux
Tags
Bash, delete, desktop.ini, erase, Remove, Thumbs.db
Comments rss Comments rss
Trackback Trackback

How To: Convert a Directory of MP3s to WAVs in Linux

r3dux | November 10, 2009

I went to burn a couple of audio CDs for the boy today, and bod-frickn-dammit if Brasero / GnomeBaker and K3B didn’t all threw their hands in the air in dismay that I might actually have the nerve to want to convert mp3s to CD-audio on the fly. Very poor.

So, as wav files come in less flavours than mp3s and tend to work first time, I knocked up a quick script to convert a directory of mp3s to .wav files using mpg123, it even handles spaces correctly after I’d given it a stern talking to… Anyways:

#/bin/bash
gotmpg123=$(which mpg123)
 
# If there's no copy of mpg123 we're not going to be doing any converting. Abort!
if [ "$gotmpg123" = "" ]; then
    echo "No copy of mpg123 found on system! Try running: sudo apt-get install mpg123"
    exit 0
fi
 
# Otherwise, if we're all set, make a directory to dump our wav files into
mkdir WAV
 
# For each file in the current directory that ends with .mp3, convert it to .wav and place in our new WAV folder
for file in ./*.mp3
do
  mpg123 -w ./WAV/"${file}".wav "$file"
done

To use the script:
- Copy and paste the above code into a new text file called mp32wav or something
- Make it executable with chmod +x mp32wav, then
- Copy it to /usr/local/bin for easy access with sudo cp mp32wav /usr/local/bin/

With that all done you can just go into a folder of mp3s in the terminal and fire it off. It’ll create a folder called WAV inside whatever directory you’re in and stick the converted wav files there with the original filename but with .wav tacked on the end.

Cheers!

Comments
2 Comments »
Categories
Coding, How-To, Linux, Music
Tags
Bash, Convert, Linux, mp3, mp32wav, mpg123, script, wav
Comments rss Comments rss
Trackback Trackback

How To: Easily Convert FLAC audio to MP3s in Linux

r3dux | September 16, 2009

I grabbed a bunch of FLAC files the other day, and as nice as they sound, I don’t think ~30-40MB per track is acceptable, so I did a bit of research and stumbled across this great post on LinuxTutorialBlog.

Turns out there’s a dead simple GUI based tool called SoundConverter – which really is as simple as pointing it at a directory and configuring your transcoding preferences (mp3, ogg, file-naming etc). A swift sudo apt-get install soundcoverter and a couple of clicks later and the job’s done.

SoundConverter1SoundConverter2

If you really want a bash method, there’s a bunch of scripts and links in tfa, such as this one by Octavio Ruiz :

#!/bin/bash
#
# Copyright 2008 Octavio Ruiz
# Distributed under the terms of the GNU General Public License v3
# $Header: $
#
# Yet Another FLAC to MP3 script
#
# Author:
# Octavio Ruiz (Ta^3) <tacvbo@tacvbo.net>
# Modification/Fixage:
# r3dux
# Thanks:
# Those comments at:
# http://www.linuxtutorialblog.com/post/solution-converting-flac-to-mp3
# WebPage:
# https://github.com/tacvbo/yaflac2mp3/tree
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY. YOU USE AT YOUR OWN RISK. THE AUTHOR
# WILL NOT BE LIABLE FOR DATA LOSS, DAMAGES, LOSS OF PROFITS OR ANY
# OTHER KIND OF LOSS WHILE USING OR MISUSING THIS SOFTWARE.
# See the GNU General Public License for more details.
 
LAME_OPTS="-V 0 -q 0 --vbr-new"
 
id3v2=$(which id3v2)
old_IFS=${IFS}
IFS=''
files=( `find . -type f -name '*flac'` )
 
for N_files in ${!files[@]}
do
vars=( `metaflac --no-utf8-convert --export-tags-to=- "${files[${N_files}]}"` )
 
for N_vars in ${!vars[@]}
do
    export "$(echo "${vars[${N_vars}]%=*}" | tr [:upper:] [:lower:])=${vars[${N_vars}]#*=}"
done
 
flac -dc "${files[${N_files}]}" |\
    lame ${LAME_OPTS} --ignore-tag-errors --add-id3v2 \
        ${artist:+--ta} ${artist} \
        ${tracknumber:+--tn} ${tracknumber} \
        ${title:+--tt} ${title} \
        ${album:+--tl} ${album} \
        ${date:+--ty} ${date} \
        ${genre:+--tg} ${genre} \
        ${comment:+--tc} ${comment} \
        - "${files[${N_files}]/\.flac/.mp3}"
 
    [[ -x ${id3v2} ]] && ${id3v2} \
        ${artist:+--artist} ${artist} \
        ${tracknumber:+--track} ${tracknumber} \
        ${title:+--song} ${title} \
        ${album:+--album} ${album} \
        ${date:+--year} ${date} \
        ${genre:+--genre} ${genre} \
        ${comment:+--comment} ${comment} \
        "${files[${N_files}]/\.flac/.mp3}"
 
done
IFS=${old_IFS}

I’ve modded the LAME_OPTS line in the above script to use the -q 0 switch in lame (so it uses the highest quality algorithm it can), and changed the order of when the ${LAME_OPTS) options are passed to lame, which results in them actually being honoured. Which is nice. Should you have any specific encoding goals, you can always browse through the lame switches and mod it to your hearts content.

Sweet like chocolate =D

Note: To run the above script, just copy & paste into a file, maybe flac2mp3.sh or something, then chmod +x flac2mp3.sh to make it executable and run it on a folder like flac2mp3.sh MyFolderOfFLACFiles.

Comments
No Comments »
Categories
How-To, Linux, Music
Tags
Audio, Bash, Conversion, FLAC, Formats, How-To, mp3, ogg, script, SoundConverter
Comments rss Comments rss
Trackback Trackback

« Previous Entries

Translate

Categories

Archives

Tags

3D ActionScript ActionScript 3.0 Adobe AI Ballarat Bash C++ Class Convert CS4 Effect Error Film Flash GLSL Gnome Hack How-To install Jaunty Java Kinect Linkage Linux Mash-Up Microsoft Motion OpenGL Particle Problem PS3 Remix Retro script Slides Sound Systems Texture Ubuntu Video VirtualBox Wii Windows XBox

Gamercard

OpenR3dux

Misc.

Flattr this

RSS Feed

r3dux twitter feed



“Help fight continental drift.”

rss Comments rss valid xhtml 1.1 design by jide powered by Wordpress get firefox