[wplug] Breaking a word into the individual characters in a shell script

Jonathan Billings billings at negate.org
Wed Aug 20 19:03:37 EDT 2008


On Aug 19, 2008, at 10:51 AM, Rob Lines wrote:

> I have dealt with using awk to grab certain columns in a file and then
> work with them as variables but now I want to take a single word and
> break it up into the individual characters for example
>
> dog and I want to assign d, o and g to separate variables to work
> with.  I looked through the awk man page and I am just not finding how
> to interact with the x character that I pass it.
>
> I may not be looking at the right tool for the job so if anyone has
> any suggestions of another tool that would work suggestions are
> welcome.
>
> The end goal is that I have a large number of files that need to be
> sorted into directories based on the name of the files (that I already
> have) and those directories are all based on the name of the file.
> for example the file dogncat_0321 would be found in
> /path/d/o/g/n/c/a/t/.  I want to pass the filename to the command and
> have it grab the first 7 characters (and always the first 7
> characters) and save each one in a seperate variable as the directory
> structure may or may not currently exist and I plan to check for the
> existence in the script and generate it on the fly if it is not
> already there.


If you're using bash, it's trivial.

Lets say that the filename is in the shell variable $filename.  You  
can set the path to be:

savepath=/path/${filename:0:1}/${filename:1:1}/${filename:2:1}/...  
(and so on)

the ${filename:0:1} is a bashism for grabbing substrings out of a  
variable.  0 is the offset (start at the beginning) and 1 is the  
number of characters to grab.

Of course, I'm too lazy to type out the whole thing (as you can see),  
so you could do this instead:

savepath="/path"
for pos in {0..6}; do
	savepath="$savepath/${filename:$pos:1}"
done

--
Jonathan Billings <billings at negate.org>




More information about the wplug mailing list