newprogrammerha
newprogrammerha

Reputation: 49

how to read line by line from a given file?

i wrote a script , and in this script i wrote a function that accepts a parameter which resembles an id , and in the function i read from a given file line by line , the file line format is :

id_num name number_of_brothers other_people_id (optional) (also there could be as many spaces between each two words and in the start )

for example :

236501 james show 3 234247 234125

(the id numbers must include only 6 digits and the name can have at the end a number, but number of brothers must be between 0-10) in this example the name is : "james show" another example:

236501 james show 3 4 234247 234125

this time the name is "james show 3" now i want to read line by line and see which line start with the given parameter and print the name..

! now in order to read line by line from the given file i used real line and at he end i did done < "$given_file"

but when i run the script from bash i get this error :

syntax error near unexpected token `}' i get this error in the last line of the following function i used in the script :

function get_name{
  while read -a line; do
  l=`echo $line`               
  if [[ `grep ^"$1" "$line"` != " " ]]; then  
   l=`cut -d" " -f2-`   
    i=1
    while(( i>0 )) ; do
      if (( ${line[i]}>=0 && $${line[i]}<11 && ( ${line[i+1]} == " " || `get_num ${line[i+1]}` == 6 ))) ; then 
         l=`cut -d " " -f1-i`
         echo "$l"
         break
     fi
    let i++
    done
  fi
  done < "$given_file"

}  ## here i get the error

what i am doing wrong in reading from the file ?

Upvotes: 1

Views: 81

Answers (1)

Jason Hu
Jason Hu

Reputation: 6333

If you just want to achieve the work, it's no more than one liner.

function get_name {
    sed -n -r "s/^$1 (.*) [0-9]{1,2}( [0-9]{6})*/\1/p" "$given_file"
}

test

$ echo 236501 james show 3 4 234247 234125 | sed -n -r 's/^236501 (.*) [0-9]{1,2}( [0-9]{6})*/\1/p'
james show 3

Upvotes: 1

Related Questions