linux - 用逗号和空格替换换行符以生成 1 行输出

标签 linux cygwin tr

示例文件

[user@linux ~]$ cat ip.txt
10.1.1.1
10.1.1.2
10.1.1.3
[user@linux ~]$

第一次尝试, 后有 1 个空格,

[user@linux ~]$ tr '\n' ', ' < ip.txt
10.1.1.1,10.1.1.2,10.1.1.3,[user@linux ~]$

第二次尝试, 前后各有 1 个空格,

[user@linux ~]$ tr '\n' ' , ' < ip.txt
10.1.1.1 10.1.1.2 10.1.1.3 [user@linux ~]$
[user@linux ~]$

第三次尝试, 之前有 1 个空格, 也产生与第二次尝试相同的输出

[user@linux ~]$ tr '\n' ' ,' < ip.txt
10.1.1.1 10.1.1.2 10.1.1.3 [user@linux ~]$
[user@linux ~]$

更新

sed 不会改变任何内容

[user@linux ~]$ sed 's/\n/, /g' ip.txt
10.1.1.1
10.1.1.2
10.1.1.3
[user@linux ~]$

虽然 perl 输出与尝试 2 和 3 类似

[user@linux ~]$ perl -pe 's/\n/ /g' ip.txt
10.1.1.1 10.1.1.2 10.1.1.3 [user@linux ~]$

所需输出

一行中 , 之后有 1 个空格,如下所示...

10.1.1.1, 10.1.1.2, 10.1.1.3

最佳答案

我相信tr只能用一个字符替换另一个字符,而不能用于插入更多字符。尝试一下这个

sed ':a;N;$!ba;s/\n/, /g' ip.txt

perl -pe 's/\n/, /g' ip.txt

如果你想转义最后一个逗号,那么

sed ':a;N;$!ba;s/\n/, /g' ip.txt | sed 's/\n$//g'

关于linux - 用逗号和空格替换换行符以生成 1 行输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56864122/

相关文章:

linux - Windows 中的 `tr` 命令是什么?

c - 是否有可能中断一个进程并检查它以便稍后恢复它?

linux - 如何删除 X 字符前的所有单词

c - 在 VS 2013 和 Cygwin 中使用 fork()

cygwin - 是否有 GNU make 的 Cygwin 版本?

linux - 无法使用 tr 转换 IP 地址

linux - GNU "time"命令测量内存使用的问题

c - socket read() 的字节偏移量 (linux)

c# - 在 c# 中使用来自 c 源的 cygwin 编译的 dll,在 socket() 、 fork() 和类似的 read write protected memory 上出错

bash - 用 tr 或类似的交换 bash 中的两个字符