The reverse of the previous simple app
Remember the bash script I wrote in the previous post? Well, the script below does the exactly opposite.
#!/bin/bash
#: Description : Reads from a file whose entries are of theĀ
format "name1 name2, age" and writes them in a file line
by line
#: Author : Thameera
#: Date : 26/12/2009
while IFS= read -r line
do
(( ${#line}==0 )) && exit 0
nm="${line%,*}"
printf "%s\n%s\n%s\n" "${nm% *}" "${nm#* }" "${line:${#nm}+2}"
done
This script widely uses parameter expansion and patterns. For example ${line%,*} removes the shortest match for a comma from the end. The percentage sign here means “remove the shortest match from the end”. The hash (#) sign used in the next line does the same thing the other way around, i.e. “remove the shortest match from the beginning”. The “shortest match” means the first match you find when you go from the end or the beginning. If you double the % or #, it will return the longest match.
For example,
$ var="anaconda"
$ echo ${var##*n}
da
And the ${#nm} expands to the length of the string nm.
When the following input is fed to the script:
chitral gamage, 32 tham sen, 30
the output is given as follows:
chitral gamage 32 tham sen 30
So that’s it. It’s just another small script, but helped me a lot to understand how parameter expansion works. See you next time with another script where the bash comes in action!
Filed under: Uncategorized | Leave a Comment

No Responses Yet to “The reverse of the previous simple app”