我目前正在尝试在 unix 上将两个文件合并在一起
第一个文件:
Tom 313.455.6786
Deena 313.899.7400
Will 313.845.5633
Nancy 313.676.9445
Kelly 313.611.4242
John 313.908.3858
第二个文件:
Deena Tuesday
Will Monday
Kelly Sunday
John Wednesday
Tom Thursday
Nancy Saturday
我正在 korn shell 中编写脚本,我需要包含 for 循环和数组以及所有这些爵士乐。
这是我到目前为止所拥有的:
#!/bin/ksh
file1=/home/file1
file2=/home/file2
set -A name
set -A phone
set -A day
for input in `cat file1| cut -d " " -f1`
do
name=$input
done
for input2 in `cat file1|cut -d " " -f2`
do
phone=$input2
done
for input3 in `cat file2|cut -d " " -f2`
do day=$input3
week= "Monday Tuesday Wednesday Thursday Friday Saturday Sunday"
for day in $week
do
echo $day\n
day=$i
done
done
printf "%s\t%-12s\t%s\n" "Name" "On-Call" "Phone"; join < (sort file1) <
(sort file2) | tr ' ' '\t'
这个脚本给了我以下输出:
Name On-Call Phone
Deena 313.899.7400 Tuesday
John 313.908.3858 Wednesday
Kelly 313.611.4242 Sunday
Nancy 313.676.9445 Saturday
Tom 313.455.6786 Thursday
Will 313.845.56334 Monday
该代码按名称字母顺序对文件进行排序,而不是按工作日排序,这正是我所需要的。它还将 On-call 输出与 Phone 输出反转。
我需要最终文件看起来像这样
Name On-Call Phone
Will Monday 313.845.5633
Deena Tuesday 313.899.7400
John Wednesday 313.908.3858
Tom Thursday 313.455.6786
Nobody Friday 313.555.3454
Nancy Saturday 313.676.9445
Kelly Sunday 313.611.4242
答案1
使用awk
它比使用 shell 更简单:
awk '
BEGIN { fmt = "%-8s%-11s%s\n" ; printf fmt, "Name", "On-Call", "Phone" }
NR==FNR { a[$1] = $2 ; next }
{ printf fmt, $1, $2, a[$1] }
' firstfile secondfile
(您可以从 Kornshell 调用该程序。)
注意:输出记录的顺序与 中记录的顺序一致secondfile
。因此,要按工作日对记录进行排序,请调整记录的顺序secondfile
(否则您需要更复杂的程序)。