A simple app to read from and output to files
This is a script I wrote to get in touch with some bash basics.
#!/bin/bash #: Description : Reads a file with entries in separated lines and write them to a file with a comma separated format #: Author : Thameera #: Date : 23/12/2009 while IFS= read -r name1 do read -r name2 read -r age if [ -z "$age" ] then break fi printf "%s %s, %s\n" "$name1" "$name2" "$age" done
What this code does is to read from a file specified in the argument list a list with the following format:
firstname1 lastname1 age1 firstname2 lastname2 age2 ....
and arrange them in the following order in a new file specified by the argument:
firstname1 lastname1, age1 firstname2 lastname2, age2
Suppose you save this file with the name main and your input is in the file in. Then the command to execute the script should be:
bash main <in >out
This will write the output in a new file called out.
When I first wrote this script, I found out that the output would produce an extra blank line with a comma. The if condition if [ -z "$age" ] was added to rectify this. This condition will break the loop when it finds that the variable age is no longer assigned to a valid value.
Well, it does not do any interesting stuff, but helped me to get touch with some basics. Hope to post some more interesting stuff in the time to come.
Filed under: Uncategorized | Leave a Comment

No Responses Yet to “A simple app to read from and output to files”