Monday, May 6, 2024
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 3422  / 2 Years ago, tue, march 1, 2022, 7:39:07

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?


More From » environment-variables

 Answers
4

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.


[#40711] Wednesday, March 2, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
urnaetted

Total Points: 10
Total Questions: 113
Total Answers: 117

Location: Burundi
Member since Sat, Aug 21, 2021
3 Years ago
urnaetted questions
;