Linux中如何实现将一列数据转换为一行数据
001、paste -s 实现
[root@pc1 test]# ls a.txt [root@pc1 test]# cat a.txt 1 2 3 4 5 [root@pc1 test]# paste -s a.txt ## paste 将一列数据转换为一行数据 1 2 3 4 5 [root@pc1 test]# paste -s -d " " a.txt ## -d参数指定间隔符 1 2 3 4 5
002、 xargs实现
[root@pc1 test]# ls a.txt [root@pc1 test]# cat a.txt 1 2 3 4 5 [root@pc1 test]# cat a.txt | xargs ## xargs将一列数据转换为一行数据 1 2 3 4 5
003、tr + sed实现
[root@pc1 test]# ls a.txt [root@pc1 test]# cat a.txt 1 2 3 4 5 [root@pc1 test]# cat a.txt | tr "\n" " " | sed 's/$/\n/' ## tr + sed将一列数据转化为一行数据 1 2 3 4 5
004、awk + sed实现
[root@pc1 test]# ls a.txt [root@pc1 test]# cat a.txt 1 2 3 4 5 [root@pc1 test]# awk '{printf("%s ", $0)} END {printf("\n")}' a.txt ## awk将一列数据转换为一行数据 1 2 3 4 5 [root@pc1 test]# awk '{printf("%s ", $0)} END {printf("\n")}' a.txt | cat -A 1 2 3 4 5 $ [root@pc1 test]# awk '{printf("%s ", $0)} END {printf("\n")}' a.txt | sed 's/[\t ]\+$//' | cat -A 1 2 3 4 5$ ## 去除末尾的空格
005、awk实现
[root@pc1 test]# ls a.txt [root@pc1 test]# cat a.txt 1 2 3 4 5 [root@pc1 test]# awk 'BEGIN{ORS = " "} {print $0}' a.txt | sed 's/ $/\n/' 1 2 3 4 5
006、awk实现
[root@pc1 test]# ls a.txt [root@pc1 test]# cat a.txt 1 2 3 4 5 [root@pc1 test]# awk 'BEGIN{RS = EOF}{gsub("\n", " "); print $0}' a.txt 1 2 3 4 5
007、sed实现
[root@pc1 test]# ls a.txt [root@pc1 test]# cat a.txt 1 2 3 4 5 [root@pc1 test]# sed ':a; N; s/\n/ /; ta' a.txt ## sed将一列数据转换为一行数据 1 2 3 4 5 [root@pc1 test]# sed ':a; N; s/\n/ /; ta' a.txt | cat -A 1 2 3 4 5$
分类:
linux shell
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2021-10-29 R语言中实现方差和标准差
2021-10-29 R语言中rbind函数和cbind的用法
2021-10-29 R语言中 %in%用法
2021-10-29 linux系统中向行末添加换行符
2021-10-29 linux 系统中实现列转行 及 行转列
2020-10-29 linux系统中的防火墙
2020-10-29 linux系统中删除逻辑卷