Monday, August 23, 2010
Thursday, August 12, 2010
Splitting strings in shell script
Nice way to pass parameters to a script is to put them in a properties file and then read the file in the script and do something with each parameter in the file. But often it is neccessary to pass more than one parameter for each line. One way to do this is to use some kind of separator between the parameters and split each line in the script using the separator. Here is one way to do it.
Example input file:
To read this file, we can use script like this:
The output should be:
Example input file:
foo:2
bar:109
baz:23
To read this file, we can use script like this:
#!/bin/sh
for LINE in `cat input_file.txt`
OLDIFS=$IFS
do
IFS=":"
arr=($LINE)
echo "First: ${arr[0]}"
echo "Second: ${arr[1]}
done
IFS=$OLDIFS
The output should be:
First: foo
Second: 2
First: bar
Second: 109
First: baz
Second: 23
Thursday, July 29, 2010
Tuesday, July 27, 2010
Subscribe to:
Posts (Atom)