Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I have a file called "krylov_methods", which has text like this:

cg     - preconditioned
cgne   - normal equations
nash   - cg subject to constraint
stcg   - another method for constraints
gmres  - general minimum residual
...

I need to extract the first word (character string) of each line, one by one, in a shell script and use it as a command line argument within that script. To extract the first word, I used the following command:

head -1 krylov_methods | tail -1 | awk '{print $1}'
head -2 krylov_methods | tail -1 | awk '{print $1}'
head -3 krylov_methods | tail -1 | awk '{print $1}'
...

This seems to work well for extracting the first word of each line one by one However, I need to be able to store the character string as a variable for future use within the script. For example, since the first word of the first line of the file "krylov_methods" is the word "cg", I want to be able store "cg" to a variable called "method". Within the script, I would like for it to get something like:

method=cg  
./execute $method  

Is this possible to store the result of the 'head' command used within a shell script?

share|improve this question
1  
To isolate the n-th line of a file is better to use sed. For example, to extract the third line: sed -n '3{p;q;}' filename. –  enzotib Jan 28 '12 at 10:51
add comment

2 Answers

up vote 2 down vote accepted

Something like this

#!/bin/bash

while read line; do
    set -- $line
    method=$1
    /path/to/execute $method
done

You could read the first word into an array as well.

http://www.thegeekstuff.com/2010/06/bash-array-tutorial/

Alternative

read can isolate each component of the line:

#!/bin/bash

while read METHOD MINUS COMMENT
do
    echo "METHOD = $METHOD"
    echo "COMMENT = $COMMENT"
    /path/to/execute $METHOD
done

sort of depends on what you are doing with the information and how you want to call it later.

share|improve this answer
    
+1 Good idea to use read. And we can improve your answer because read can isolate the components of the line => it simplifies the script (and make it more portable ;). I preferred to edit your answer instead of adding another one ;-) –  olibre Jan 28 '12 at 9:12
add comment

Actually, after some experimenting, I figured it out:

method=$(head -$i krylov_methods | tail -1 | awk '{print $1}')
execute $method
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.