2

I am working on a bash project. I need to get all the values (one at a time because I will be using them somewhere else) from a text file. The text file I will be getting is structured like this:

Report:
-----------
Name  Column1  Column2  Column3  Column4
row1  val1     val2     val3     val4     
row2  val5     val6     val7     val8     
row3  val9     val10    val11    val12  

There are no fixed amount of rows and columns so I will need something general. How do I retrieve each val one by one in bash? Thanks.

3
  • Does the val means any value(a combination of numbers or letters)? Jun 18 '14 at 17:10
  • @AvinashRaj Yes a value can be either a number, letters or combination of both
    – Redson
    Jun 18 '14 at 17:11
  • Please don't crosspost...
    – jasonwryan
    Jun 18 '14 at 19:43
3

You can process content of a file line by line, using bash while loop:

i=1

while IFS= read -a line; do
  printf "Line number %d:\n" $i
  printf "%s\n" "${line[@]}"
  let i++
done < "file.txt"

Each line is stored in array line, you can get each element of array line by syntax:

echo "${line[n]}"

where n is the order of element in array.

3

And through awk command,

$ awk '/^Report|^-----|^Name/ {next}{for (i=2;i<=NF;i++){print $i}}' file
val1
val2
val3
val4
val5
val6
val7
val8
val9
val10
val11
val12

It skips the line starts with Report,---,Name and it prints all the values from the second column to the end for each line. The values are printed in a newline.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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