LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Red Hat (https://www.linuxquestions.org/questions/red-hat-31/)
-   -   how to read certain line of file, and output to variable? (https://www.linuxquestions.org/questions/red-hat-31/how-to-read-certain-line-of-file-and-output-to-variable-550213/)

jimmyjiang 04-30-2007 03:34 PM

how to read certain line of file, and output to variable?
 
hi,
I have a file : arg.txt
oi1 oi2 oi3 oi4
k2 k3
l4 l5 l6

the line nubmers are fixed.but elements in each line are seperated by space and their numbers are random, not always same. that's mean, next time you read arg.txt maybe will looks like this:

oi1 oi2 oi3 oi4 oi5
k2 k3
l4 l5 l6

how to read certain line of file, and put each element in certain line to variables.
for exmple,I want to output line 1 to variables:

line1=getline 1 arg.txt # this is only a assume,not real code.
y=(number of line1) # I don't know how to get it.
for (( i =0; i<=y; i++ ))
do
argi=$i
done

#arg1 arg2 arg3 ...arg(y-1) are source files, argy are desionation directory.
cp arg1 arg2 arg3 ...arg(y-1) argy


I'm new to bash script,sorry for the mess.
thanks!

osor 04-30-2007 04:52 PM

First off, I don’t see what this has to do with Red Hat…

As for your problem, the most elegant solution involves bash arrays like so:
Code:

while read fullline; do
        line=(${fullline})
        y=${#line[*]}

        for i in $(seq 0 $(($y - 1))); do
                echo -n "${line[$i]} "
        done; echo

#        echo ${line[*]}
#        cp ${line[*]}
done < arg.txt

This code sample reads in one line at a time to the variable “fullline”. In each iteration of the outer loop, an array called “line” is declared with contents of $fullline, but each in a separate index of the array. So you could access each element of the array by index, starting at 0 (for example, in the first iteration of the loop, if you said “echo ${line[2]}”, it would output “oi3”). You can access all the elements of the array with spaces in between with “${line[*]}”, and you can access the number of elements with “${#line[*]}”. The for loop simply prints each element followed by a space, and a final newline (the same thing could more easily have been accomplished by uncommenting the line in blue). If you change, for example, the number in red from “1” to “2”, you print out all but the last element (i.e., arg1 arg2 arg3 … arg(y-1)). Finally, the line in green (if uncommented) does what you ask — “cp arg1 arg2 arg3 … arg(y-1) argy”.

I suggest you read up on bash arrays. If you have any questions, just post.

jimmyjiang 05-01-2007 08:46 AM

thanks! it works!


All times are GMT -5. The time now is 03:21 PM.