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

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

问题描述

我遇到了一点问题,我整天都在搜索.这是我的第一个 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

我有两个文本文件

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

file2

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 }'

您可以使用制表符 ( ) 代替空格作为连接符,以获得格式良好的输出.

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

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

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