View Full Version : Bash help: Find first n characters in a string?

28th December 2004, 08:02 AM
I checked out the Advanced Bash Guide (http://howtos.linux.com/guides/abs-guide/) but I couldn't find what I need.

I need to get the first 2 digits of a string and store to a variable, and then I need the 4th and on to another. There's a function in VB.NET (I know, super lame, I took a class in it tho) that does it and it's like Microsoft.VisualBasic.Left("String",3) and it returns "Srt" or something.

Here's my practical use: I'm trying to convert all of my iTunes AAC files to MP3s so I can use them in my car. So far, I've figured out how to convert all of the files to MP3...

for i in *.m4a; do faad -w "$i" | lame - "`basename "$i" '.m4a'`.mp3"; done

Problem is, I'd like to also create ID3 tags automatically. With the filename alone, I can get the track number and song title, because each file is like "03 Melissa.m4a". I can remove the .m4a by using $basename "$i" '.m4a' but that still leaves the "03 " in front.

I ultimately want it to be for i in *.m4a; do faad -w "$i" | lame --tt "Track Title" --tn TrackNumber - "`basename "$i" '.m4a'`.mp3"; done but I don't know what kind of text manipulation it would take to achieve this.

Any help would be MUCH appreciated!!!! Thanks!!!!


28th December 2004, 08:09 AM
Should I be trying something other than bash? This doesn't sound too advanced, but I don't know enough of the other languages to whip something up. I know SOME perl and SOME php, but I don't know how to run anything similar to the for, done thing in either language. This doesn't seem too difficult so I little shove in the right direction would be great!

29th December 2004, 01:16 AM
You probably want to put this in a script instead of one long line, as it may get complicated. That guide shows how.

Read the string manipulation part of the bash guide, substring extraction especially.

You can get the substring of the number and then the title, store them in variables, then use them in the command. For example:

FILE=`basename "$i" '.m4a'`

I think this will work but I have not tried it. And then you can execute your command, but with these variables.

29th December 2004, 06:53 PM
Thanks, I didn't know what to even call it... subtraction, now I know. I was thinking crop or something but I knew that couldn't be right.

Thanks again!