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.

#: 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
 (( ${#line}==0 )) && exit 0
 printf "%s\n%s\n%s\n" "${nm% *}" "${nm#* }" "${line:${#nm}+2}"

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}

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:


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!


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

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: