合并两个文件中的文本,输出到另一个文件 [英] Combine text from two files, output to another

查看:164
本文介绍了合并两个文件中的文本,输出到另一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我一直都在搜索.这是我的第一个Unix类,不要太苛刻.

i'm having a bit of a problem and i've been searching allll day. this is my first Unix class don't be to harsh.

这听起来很简单,但我听不懂

so this may sound fairly simple, but i can't get it

我有两个文本文件

文件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

文件2

Roberto Tuesday‭ ‬2
Sally Monday‭ ‬8
Ted Sunday‭ ‬16
Alice Wednesday‭ ‬23
David Thursday‭ ‬10
Mary Saturday‭ ‬14
Frank Friday‭ ‬15

我正在尝试使用循环结构来编写脚本,该结构将合并两个文件并在下面的输出中作为一个单独的文件出现

I am trying to write a script using a looping structure that will combine both files and come out with the output below as a separate file

输出:

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

这就是我尝试过的(我知道这很可怕)

This is what i tried( i know its horrible)

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"

任何帮助将不胜感激

推荐答案

首先,使用sort对文件进行排序,然后使用以下命令:

First, sort the files using sort and then use this command:

paste file1 file2 | awk '{print $1,$4,$2,$5}'

这将使您更加接近.之后,您必须弄清楚如何将时间从24小时格式格式化为12小时格式.

This will bring you pretty close. After that you have to figure out how to format the time from the 24 hour format to the 12 hour format.

如果要避免单独使用sort,可以增加一些复杂性,例如:

If you want to avoid using sort separately, you can bring in a little more complexity like this:

paste <(sort file1) <(sort file2) | awk '{print $1,$4,$2,$5}'

最后,如果您还没有弄清楚如何以12小时格式打印时间,请使用以下完整命令:

Finally, if you have not yet figured out how to print the time in 12 hour format, here is your full command:

paste <(sort file1) <(sort file2) | awk '{"date --date=\"" $5 ":00:00\" +%I%P" |& getline $5; print $1 " " $4 " " $2 " " $5 }'

您可以使用制表符(\ t)代替空格作为连接器,以获取格式正确的输出.

You can use tabs (\t) in place of spaces as connectors to get a nicely formatted output.

这篇关于合并两个文件中的文本,输出到另一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆