linux中如何将一列数据转换为一行数据

1、生成测试数据

root@PC1:/home/test# ls
a.txt
root@PC1:/home/test# cat a.txt   ## 测试数据
1
2
3
4
5

 

2、xargs实现

复制代码
root@PC1:/home/test# ls
a.txt
root@PC1:/home/test# cat a.txt
1
2
3
4
5
root@PC1:/home/test# cat a.txt | xargs
1 2 3 4 5
复制代码

 

3、awk实现

复制代码
root@PC1:/home/test# ls
a.txt
root@PC1:/home/test# cat a.txt
1
2
3
4
5
root@PC1:/home/test# cat a.txt | awk '{printf("%s ", $0)} END {printf("\n")}' | cat -A
1 2 3 4 5 $
root@PC1:/home/test# cat a.txt | awk '{printf("%s ", $0)} END {printf("\n")}' | sed 's/.$//' | sed -n l
1 2 3 4 5$
复制代码

 

4、paste实现

复制代码
root@PC1:/home/test# ls
a.txt
root@PC1:/home/test# cat a.txt
1
2
3
4
5
root@PC1:/home/test# cat a.txt | paste -s
1       2       3       4       5
root@PC1:/home/test# cat a.txt | paste -s -d " "
1 2 3 4 5
root@PC1:/home/test# cat a.txt | paste -s -d " " | cat -A
1 2 3 4 5$
复制代码

 

5、tr实现

复制代码
root@PC1:/home/test# ls
a.txt
root@PC1:/home/test# cat a.txt
1
2
3
4
5
root@PC1:/home/test# cat a.txt | tr "\n" " " | sed 's/.$/\n/'
1 2 3 4 5
root@PC1:/home/test# cat a.txt | tr "\n" " " | sed 's/.$/\n/' | sed -n l
1 2 3 4 5$
复制代码

 

6、利用内置变量RS实现

复制代码
root@PC1:/home/test# ls
a.txt
root@PC1:/home/test# cat a.txt
1
2
3
4
5
root@PC1:/home/test# awk 'BEGIN{RS = EOF} {gsub("\n", " "); print}' a.txt
1 2 3 4 5
root@PC1:/home/test# awk 'BEGIN{RS = EOF} {gsub("\n", " "); print}' a.txt | cat -A
1 2 3 4 5$
复制代码

 

7、利用RS、ORS内置变量实现

复制代码
root@PC1:/home/test# ls
a.txt
root@PC1:/home/test# cat a.txt
1
2
3
4
5
root@PC1:/home/test# cat a.txt | awk '{RS = "\n"; ORS = " "} {print}'
1 2 3 4 5 root@PC1:/home/test# cat a.txt | awk '{RS = "\n"; ORS = " "} {print} END {printf("\n")}'
1 2 3 4 5
root@PC1:/home/test# cat a.txt | awk '{RS = "\n"; ORS = " "} {print} END {printf("\n")}'
1 2 3 4 5
root@PC1:/home/test# cat a.txt | awk '{RS = "\n"; ORS = " "} {print} END {printf("\n")}' | cat -A
1 2 3 4 5 $
root@PC1:/home/test# cat a.txt | awk '{RS = "\n"; ORS = " "} {print} END {printf("\n")}' | sed 's/.$//' | cat -A
1 2 3 4 5$
复制代码
复制代码
root@PC1:/home/test# ls
a.txt
root@PC1:/home/test# cat a.txt
1
2
3
4
5
root@PC1:/home/test# cat a.txt | awk '{ORS = " "} {print} END {printf("\n")}'
1 2 3 4 5
root@PC1:/home/test# cat a.txt | awk '{ORS = " "} {print} END {printf("\n")}' | cat -A
1 2 3 4 5 $
root@PC1:/home/test# cat a.txt | awk '{ORS = " "} {print} END {printf("\n")}' | sed 's/ $//' | cat -A
1 2 3 4 5$
复制代码

 

8、sed实现

复制代码
root@PC1:/home/test# ls
a.txt
root@PC1:/home/test# cat a.txt
1
2
3
4
5
root@PC1:/home/test# cat a.txt | sed ':a; N; s/\n/ /; ta'
1 2 3 4 5
root@PC1:/home/test# cat a.txt | sed ':a; N; s/\n/ /; ta' | sed -n l
1 2 3 4 5$
复制代码

 

posted @   小鲨鱼2018  阅读(549)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
历史上的今天:
2021-03-22 c语言中数组中元素的个数
点击右上角即可分享
微信分享提示