Wednesday, 23 January 2013 13:56

Reading command parameters from file with grep and awk

Written by 
Rate this item
(0 votes)

I was facing the problem today that I wanted to read the command line arguments for a program from a configuration file. I did also need to check the return value of the command executed.

Consider you have the following configuration file :

monte@raspberrypi ~ $ cat toolconfig


You could then use grep to extract all lines that start with „parameter“

monte@raspberrypi ~ $ grep ^parameter toolconfig

If you pipe the output of grep to awk and tell awk to split the lines by the comma you are half way there.

monte@raspberrypi ~ $ grep ^parameter toolconfig | awk -F',' '{ print " "$1 " " $2 " " $3 " " $4 }'
parameter 1 "FIRST" 0x100
parameter 2 "SECOND" 0x200
parameter 3 "THIRD" 0x300

The next step is to format the call that needs to be executed. In this example we simple execute the echo command. Since the first entry „parameter“ is only for identification we skip it with the next call. For now we do not execute anything but do only display the command.

monte@raspberrypi ~ $ grep ^parameter toolconfig | awk -F',' '{ print "echo -a " $2 " -b " $3 " -c " $4 }'
echo -a 1 -b "FIRST" -c 0x100
echo -a 2 -b "SECOND" -c 0x200
echo -a 3 -b "THIRD" -c 0x300

Many implementations of awk support the system command to execute other commands. The following line will execute the echo command with the options specified in the config file.

monte@raspberrypi ~ $ grep ^parameter toolconfig | awk -F',' '{ system( "echo -a " $2 " -b " $3 " -c " $4 ) }'
-a 1 -b FIRST -c 0x100
-a 2 -b SECOND -c 0x200
-a 3 -b THIRD -c 0x300

Awk works on a line by line basis. This means that the command surrounded by {} is executed for each line in our file (or each line provided by grep here). If we call a complex program with system it might report an error and we need to stop processing the other entries. This can be done by checking the return value of system.

monte@raspberrypi ~ $ grep ^parameter toolconfig | awk -F',' '{ if( system( "echo -a " $2 " -b " $3 " -c " $4 ) != 0 ) exit 1 }'
-a 1 -b FIRST -c 0x100
-a 2 -b SECOND -c 0x200
-a 3 -b THIRD -c 0x300
monte@raspberrypi ~ $ echo $?

If the echo command would fail for any of the lines the processing of the left over lines would stop. The return value which can be obtained with $? would be not equal to zero.

Happy scripting.

Read 849 times Last modified on Friday, 26 June 2015 11:41

Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.