文本文件数据解析行和输出为列(Text File data parsing lines and output as columns)

编程入门 行业动态 更新时间:2024-10-28 17:17:30
文本文件数据解析行和输出为列(Text File data parsing lines and output as columns)

我试图解析一个测试文件。 该文件具有以下格式的用户名,地址和电话号码:

Name: John Doe1 address : somewhere phone: 123-123-1234 Name: John Doe2 address : somewhere phone: 123-123-1233 Name: John Doe3 address : somewhere phone: 123-123-1232

只有几乎10k用户:)我想要做的是将这些行转换为列,例如:

Name: John Doe1 address : somewhere phone: 123-123-1234 Name: John Doe2 address : somewhere phone: 123-123-1233 Name: John Doe3 address : somewhere phone: 123-123-1232

我宁愿用bash来做,但如果你知道如何在python中做到这一点,那么这个信息的文件位于/ root / docs / information中。 任何提示或帮助将不胜感激。

I'm trying to parse a test file. the file has username, address and phone in the following format:

Name: John Doe1 address : somewhere phone: 123-123-1234 Name: John Doe2 address : somewhere phone: 123-123-1233 Name: John Doe3 address : somewhere phone: 123-123-1232

Only for almost 10k users: ) what I would like to do is convert those rows to columns, for example:

Name: John Doe1 address : somewhere phone: 123-123-1234 Name: John Doe2 address : somewhere phone: 123-123-1233 Name: John Doe3 address : somewhere phone: 123-123-1232

I would prefer to do it in bash but if you know how to do it in python that would be great too, the file that has this information is in /root/docs/information. Any tips or help would be much appreciated.

最满意答案

GNU awk一种方法:

awk 'BEGIN { FS="\n"; RS=""; OFS="\t\t" } { print $1, $2, $3 }' file.txt

结果:

Name: John Doe1 address : somewhere phone: 123-123-1234 Name: John Doe2 address : somewhere phone: 123-123-1233 Name: John Doe3 address : somewhere phone: 123-123-1232

请注意,我已将输出文件分隔符( OFS )设置为两个制表符( \t\t )。 您可以将其更改为您喜欢的任何角色或一组角色。 HTH。

One way with GNU awk:

awk 'BEGIN { FS="\n"; RS=""; OFS="\t\t" } { print $1, $2, $3 }' file.txt

Results:

Name: John Doe1 address : somewhere phone: 123-123-1234 Name: John Doe2 address : somewhere phone: 123-123-1233 Name: John Doe3 address : somewhere phone: 123-123-1232

Note that, I've set the output file separator (OFS) to two tab characters (\t\t). You can change this to whatever character or set of characters you please. HTH.

更多推荐

本文发布于:2023-08-06 13:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1448597.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本文件   数据   File   Text   data

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!