简洁便携的“加入"在 Unix 命令行上 [英] Concise and portable "join" on the Unix command-line

查看:55
本文介绍了简洁便携的“加入"在 Unix 命令行上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将多行合并为一行,在换行符所在的位置使用分隔符,并避免尾随分隔符,并且可以选择忽略空行?

How can I join multiple lines into one line, with a separator where the new-line characters were, and avoiding a trailing separator and, optionally, ignoring empty lines?

示例.考虑一个包含三行的文本文件 foo.txt:

Example. Consider a text file, foo.txt, with three lines:

foo
bar
baz

所需的输出是:

foo,bar,baz

我现在使用的命令:

tr '\n' ',' <foo.txt |sed 's/,$//g'

理想情况下应该是这样的:

Ideally it would be something like this:

cat foo.txt |join ,

是什么:

  1. 最便携、简洁、易读的方式.
  2. 使用非标准 unix 工具的最简洁方法.

当然我可以写一些东西,或者只是使用别名.但我很想知道这些选项.

Of course I could write something, or just use an alias. But I'm interested to know the options.

推荐答案

也许有点令人惊讶,paste 是一个很好的方法:

Perhaps a little surprisingly, paste is a good way to do this:

paste -s -d","

这不会处理您提到的空行.为此,首先通过 grep 管道您的文本:

This won't deal with the empty lines you mentioned. For that, pipe your text through grep, first:

grep -v '^$' | paste -s -d"," -

这篇关于简洁便携的“加入"在 Unix 命令行上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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