View Single Post
Posts: 838 | Thanked: 292 times | Joined on Apr 2010
#15
Originally Posted by sdstrowes View Post
Great! I hope you don't mind if I offer a couple of helpful comments on your code...

Code:
#!/bin/bash
convert=

case $1 in
group) convert=$(echo 1) ;;
album) convert=$(echo 2) ;;
label) convert=$(echo 3) ;;
year) convert=$(echo 4) ;;
*) echo "please input group, album, label, or year." ; exit 1 ;;
esac 

cut -f$(echo $convert) -d\| albums
You can tidy this slightly:

Code:
#!/bin/bash
case $1 in
	group) convert=1 ;;
	album) convert=2 ;;
	label) convert=3 ;;
	year) convert=4 ;;
	*) echo "please input group, album, label, or year."
	   exit 1 ;;
esac 

cut -f$convert -d\| albums
So the substitution of convert drops straight in place on your 'cut' command.

Another really useful tool to learn is AWK. You could replace your 'cut' command with a simple 'awk' program:
Code:
awk 'BEGIN {FS="|"} {print $'$convert'}' albums
To explain, AWK operates on each line in a file. AWK treats each line as a series of fields ($1 is the first, $2 is second, $0 is the entire line). Here, I've set the field separator (FS) to the pipe character ("|") before any lines of text have been read, and I've told AWK to print out the correct field on each line. It may be a bit more verbose than cut in this example, but AWK is a powerful tool which I use all the time.

Good luck and happy coding!
wow you actually read my code?! thanks I now see cut the echo's in the case statement. I thought any time you needed to get the value from a variable you had to use echo? no I guess not. I will investigate your awk command further, I know a tiny about it but know it is its own programming language and am scared to even look at the chapter on it in my book