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 @   小鲨鱼2018  阅读(809)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2022-09-30 linux 中如何升级glibc 版本
2022-09-30 linux中查看GLIBC版本
2022-09-30 python3 ./gen_ldc_version_info.py > utils/ldc_version_info_.d make: *** [utils/ldc_version_info_.d] Error 1
2022-09-30 centos7中升级make到最新版本
2022-09-30 centos7如何升级GCC编辑器、G++编译器, 安装多个版本及切换
2021-09-30 c primer plus 12 编程练习
2020-09-30 beagle 填充 Exception in thread "main" java.lang.IllegalArgumentException: NaN
点击右上角即可分享
微信分享提示