0

I am working on a project in which I need to have portions of a data file read into variables (last name, first name, room, etc) to be displayed in a paragraph, which is then looped until every name is covered.

The datafile is:

James,Robert,M,E162K,5101 Evergreen, Dearborn,Mi,48128
Fulton,Brent,M,E162I,5101 Evergreen, Dearborn,Mi,48128
Conner,Marrci,F,P262J,5101 Evergreen, Dearborn,Mi,48128
Conti,Anthony,M,P252F,5101 Evergreen, Dearborn,Mi,48128

And it needs to be fed into the following text: Where the variables listed are replaced with the corresponding names:

echo "Dear Mr/Mrs. $lastName" >>project2.output
echo "Welcome to Widgets, Inc. $firstName. This letter is to inform you of your assigned office space at
Widgets, Inc. is in the main $building  building. Your office is $room located at 5101 Evergreen,
Dearborn Mi. 48121.

I am not sure how to do this so any help would be much appreciated!

2
  • using... which language? Unix is an operating system, are you trying to do this in some kind of shell? If so, which one? And if so: any reason you're doing this on the shell rather than a general purpose scripting language like perl, python, or node? Commented Nov 22, 2016 at 19:54
  • Given the echo statements, I'm guessing you are looking at a shell script, maybe bash. In which case, something like while IFS=, read lname fname initial room address city state zip; do ..... done < input.txt is probably a good place to start
    – twalberg
    Commented Nov 22, 2016 at 20:06

1 Answer 1

5

What about this?

#!/usr/bin/env bash

while IFS="," read -r firstName lastName Sex building address city state zip; do
    echo -ne "Dear Mr/Mrs. $lastName, \n"
    echo "Welcome to Widgets, Inc. $firstName. This letter is to inform you of your assigned office space at Widgets, Inc. is in the main $building  building. Your office is $room located at $address,$city $state $zip"
done < datafile
4
  • should the 'datafile' in 'done < datafile' be the input or output file?
    – Copache
    Commented Nov 22, 2016 at 20:13
  • 'datafile' here is the input file. Its taking the standard in. Commented Nov 22, 2016 at 20:14
  • Thank you. It worked. I had never heard of the IFS command before. Very useful!
    – Copache
    Commented Nov 22, 2016 at 20:23
  • IFS is a shell variable, not a command. It is controlling how the read command splits the incoming line into fields. When you use var=value some_command, you are setting an environment variable for the strict use of some_command without affecting the currently running shell. Commented Nov 22, 2016 at 20:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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