-1

How do I read the contents of a file and then put them into different variables in another script?

For example, let's say this is student_1.item, which contains exactly these three lines:

student_1 Sally Johnson
8 1 
Mr. Ortiz

In another script, say script1.bash, I want to read the values in script2.bash and print the information so that the following is displayed:

Student number: student_1
Student name: Sally Johnson
Age: 8
Grade Level: 1
Teacher: Mr. Ortiz

How do I do this without using find, grep, sed, and awk?

  • 1
    Is this homework? – jordanm Sep 17 '20 at 22:00
  • This is a good read https://stackoverflow.com/questions/10929453/read-a-file-line-by-line-assigning-the-value-to-a-variable – thanasisp Sep 17 '20 at 22:06
  • The concept is what I need help with for a lab assignment, yes. – justanotherstudent Sep 17 '20 at 22:06
  • It's unclear why you need 2 scripts to acheieve your output. You'll need to show more code here for us to understand that. Good luck. – shellter Sep 17 '20 at 22:27
  • Bizarrely we often get the question "how do I read a file line per line, even if there are spaces in the lines?". Here you want the opposite. **If** your input file will always be that format, you could do that. It uses a `for` loop. – Nic3500 Sep 18 '20 at 00:04

1 Answers1

1

With three read commands and a printf:

{ read num name; read age gl; read teacher; } < student_1.item 
printf \
'Student number: %s
Student name: %s
Age: %s
Grade Level: %s
Teacher: %s\n' $num "$name" $age $gl "$teacher"

Output:

Student number: student_1
Student name: Sally Johnson
Age: 8
Grade Level: 1
Teacher: Mr. Ortiz
agc
  • 7,973
  • 2
  • 29
  • 50