Blogs Directory

Thursday, June 27, 2013

Assign output of the command to a variable in Shell Script


      We come across various situations where we need to dump the output of the analysis into an excel sheet to publish the result of analysis. In one of the situations i needed to make an csv format of the output analysis. This requires the computed values to be presented in a row for each entity.
       We know that our script works sequentially line by line. If you want to print a value in the current line u need to calculate it before to do so. But we can actually have multiple commands embedded in one line. The sub commands would execute first and later the parent command.

Example :

If you need the output file to have count based on the various grep patterns in one line you can do so like this,

set count1 = `grep "pattern1" filename | wc`
set count2 = `grep "pattern2" filename | wc`
set count3 = `grep "pattern3" filename | wc`
set count4 = `grep "pattern4" filename | wc`

echo "The counts are : $count1 , $count2 , $count3 , $count4" > outputfile

`-  back tick is used here. This can be used for executing a command inside another command. 

No comments :

Post a Comment