bash - Read a file line by line assigning the value to a variable -


i have following .txt file:

marco paolo antonio 

i want read line-by-line, , each line want assign .txt line value variable. supposing variable $name, flow is:

  • read first line file
  • assign $name = "marco"
  • do tasks $name
  • read second line file
  • assign $name = "paolo"

the following (save rr.sh) reads file passed argument line line:

#!/bin/bash while ifs='' read -r line || [[ -n "$line" ]];     echo "text read file: $line" done < "$1" 

explanation:

  • ifs='' (or ifs=) prevents leading/trailing whitespace being trimmed.
  • -r prevents backslash escapes being interpreted.
  • || [[ -n $line ]] prevents last line being ignored if doesn't end \n (since read returns non-zero exit code when encounters eof).

run script follows:

chmod +x rr.sh ./rr.sh filename.txt 

....


Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -