linux 中删除文本中所有的换行符

发布时间 2023-09-30 21:57:57作者: 小鲨鱼2018

 

001、tr实现

[root@pc1 test02]# ls
a.txt
[root@pc1 test02]# cat a.txt      ## 测试文件
01 02
03 04
05 06
07 08
09 10
[root@pc1 test02]# cat a.txt | tr "\n" " "       ## 删除所有的换行符
01 02 03 04 05 06 07 08 09 10 [root@pc1 test02]# cat a.txt | tr "\n" " " | sed 's/ $//'   ## 删除末尾的空格
01 02 03 04 05 06 07 08 09 10[root@pc1 test02]#

 

002、awk实现

[root@pc1 test02]# ls
a.txt
[root@pc1 test02]# cat a.txt                ## 测试数据
01 02
03 04
05 06
07 08
09 10
[root@pc1 test02]# awk '{printf("%s ", $0)}' a.txt     ## 删除末尾的空格
01 02 03 04 05 06 07 08 09 10 [root@pc1 test02]#

 

003、sed实现, 会保留最后的一个空格

[root@pc1 test02]# ls
a.txt
[root@pc1 test02]# cat a.txt            ## 测试数据
01 02
03 04
05 06
07 08
09 10
[root@pc1 test02]# sed ':t; N; s/\n/ /; b t' a.txt     ## 删除所有的换行符
01 02 03 04 05 06 07 08 09 10

 

004、awk实现

[root@pc1 test02]# ls
a.txt
[root@pc1 test02]# cat a.txt             ## 测试数据
01 02
03 04
05 06
07 08
09 10
[root@pc1 test02]# awk 'BEGIN{ORS = " "} {print $0}' a.txt     ## 直接指定了输出的换行符
01 02 03 04 05 06 07 08 09 10 [root@pc1 test02]#

 。