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 @ 2022-03-22 21:48  小鲨鱼2018  阅读(522)  评论(0编辑  收藏  举报