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

 

001、tr实现

a、

[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]#

 

b、

[root@pc1 test]# ls
a.txt
[root@pc1 test]# cat a.txt                   ## 测试文件
01 02
03 04
05 06
07 08
09 10
[root@pc1 test]# cat a.txt | tr -d "\n"      ## 直接删除换行符
01 0203 0405 0607 0809 10[root@pc1 test]#

 

c、

[root@pc1 test]# ls
a.txt
[root@pc1 test]# cat a.txt         
01 02
03 04
05 06
07 08
09 10
[root@pc1 test]# cat a.txt | tr "\n" "\0"      ## 其中\0表示空白字符NULL,或者ASCII码中的0
01 0203 0405 0607 0809 10[root@pc1 test]#

 

 

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]#

 。

 

posted @ 2023-09-30 21:50  小鲨鱼2018  阅读(641)  评论(0编辑  收藏  举报