所以这听起来可能相当简单,但我无法理解
我有两个文本文件
文件1
David 734.838.9801
Roberto 313.123.4567
Sally 248.344.5576
Mary 313.449.1390
Ted 248.496.2207
Alice 616.556.4458
Frank 634.296.1259
file2的
Roberto Tuesday 2
Sally Monday 8
Ted Sunday 16
Alice Wednesday 23
David Thursday 10
Mary Saturday 14
Frank Friday 15
我正在尝试使用循环结构编写脚本,该结构将两个文件合并,并将下面的输出作为单独的文件出现
输出:
Name On-Call Phone Start Time
Sally Monday 248.344.5576 8am
Roberto Tuesday 313.123.4567 2am
Alice Wednesday 616.556.4458 11pm
David Thursday 734.838.9801 10am
Frank Friday 634.296.1259 3pm
Mary Saturday 313.449.1390 2pm
Ted Sunday 248.496.2207 4pm
这是我试过的(我知道它很可怕)
echo " Name On-Call Phone Start Time"
file="/home/xubuntu/date.txt"
file1="/home/xubuntu/name.txt"
while read name2 phone
do
while read name day time
do
echo "$name $day $phone $time"
done<"$file"
done<"$file1"
任何帮助将不胜感激
答案 0 :(得分:2)
首先,使用sort
对文件进行排序,然后使用此命令:
paste file1 file2 | awk '{print $1,$4,$2,$5}'
这会让你非常接近。之后,您必须弄清楚如何格式化从24小时格式到12小时格式的时间。
如果您想避免单独使用sort
,可能会带来更多这样的复杂性:
paste <(sort file1) <(sort file2) | awk '{print $1,$4,$2,$5}'
最后,如果您还没有想出如何以12小时格式打印时间,这是您的完整命令:
paste <(sort file1) <(sort file2) | awk '{"date --date=\"" $5 ":00:00\" +%I%P" |& getline $5; print $1 " " $4 " " $2 " " $5 }'
您可以使用制表符(\ t)代替空格作为连接符,以获得格式良好的输出。
答案 1 :(得分:2)
在这种情况下,join command
也可以使用,
join -1 1 -2 1 <(sort file1) <(sort file2)
<强>描述强>
-1 -> file1
1 -> first field of file1 (common field)
-2 -> file2
1 -> first field of file2 (common field)
**cat file1**
David 734.838.9801
Roberto 313.123.4567
Sally 248.344.5576
Mary 313.449.1390
Ted 248.496.2207
Alice 616.556.4458
Frank 634.296.1259
**cat file2**
Roberto Tuesday 2
Sally Monday 8
Ted Sunday 16
Alice Wednesday 23
David Thursday 10
Mary Saturday 14
Frank Friday 15
Alice 616.556.4458 Wednesday 23
David 734.838.9801 Thursday 10
Frank 634.296.1259 Friday 15
Mary 313.449.1390 Saturday 14
Roberto 313.123.4567 Tuesday 2
Sally 248.344.5576 Monday 8
Ted 248.496.2207 Sunday 16