UNIX(Bash):将字符串拆分为要在文本中使用的变量

时间:2016-11-22 19:47:38

标签: bash unix

我正在开发一个项目,我需要将一部分数据文件读入变量(姓氏,名字,房间等),以便在段落中显示,然后循环,直到覆盖每个名称

数据文件是:

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

需要将其输入以下文本:列出的变量用相应的名称替换:

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.

我不知道如何做到这一点,所以任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:5)

这个怎么样?

#!/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