zoukankan      html  css  js  c++  java
  • linux shell实现将多行数据转换为指定行数据

    1、创建测试数据

    root@PC1:/home/test/test# seq -f %02g 40 | awk '{if(NR % 4 == 0) {print $0} else {printf("%s ", $0)}}'  ## 利用seq命令产生连续数字,然后利用awk分配行
    01 02 03 04
    05 06 07 08
    09 10 11 12
    13 14 15 16
    17 18 19 20
    21 22 23 24
    25 26 27 28
    29 30 31 32
    33 34 35 36
    37 38 39 40
    root@PC1:/home/test/test# seq -f %02g 40 | awk '{if(NR % 4 == 0) {print $0} else {printf("%s ", $0)}}' > test.txt
    root@PC1:/home/test/test# ls
    test.txt
    root@PC1:/home/test/test# cat test.txt
    01 02 03 04
    05 06 07 08
    09 10 11 12
    13 14 15 16
    17 18 19 20
    21 22 23 24
    25 26 27 28
    29 30 31 32
    33 34 35 36
    37 38 39 40

    2、将2行转换为1行

    root@PC1:/home/test/test# cat test.txt
    01 02 03 04
    05 06 07 08
    09 10 11 12
    13 14 15 16
    17 18 19 20
    21 22 23 24
    25 26 27 28
    29 30 31 32
    33 34 35 36
    37 38 39 40
    root@PC1:/home/test/test# awk '{if(NR % 2 == 0) {print $0} else {printf("%s\t",$0)}}' test.txt  ## 行号能被2整除,打印换行符,否则不打印
    01 02 03 04     05 06 07 08
    09 10 11 12     13 14 15 16
    17 18 19 20     21 22 23 24
    25 26 27 28     29 30 31 32
    33 34 35 36     37 38 39 40

    或sed实现:

    root@PC1:/home/test/test# cat test.txt
    01 02 03 04
    05 06 07 08
    09 10 11 12
    13 14 15 16
    17 18 19 20
    21 22 23 24
    25 26 27 28
    29 30 31 32
    33 34 35 36
    37 38 39 40
    root@PC1:/home/test/test# sed "N; s/\n/\t/" test.txt  ## N表示可以把两行当做一行处理
    01 02 03 04     05 06 07 08
    09 10 11 12     13 14 15 16
    17 18 19 20     21 22 23 24
    25 26 27 28     29 30 31 32
    33 34 35 36     37 38 39 40

    3、将3行转换为1行

    root@PC1:/home/test/test# cat test.txt
    01 02 03 04
    05 06 07 08
    09 10 11 12
    13 14 15 16
    17 18 19 20
    21 22 23 24
    25 26 27 28
    29 30 31 32
    33 34 35 36
    37 38 39 40
    root@PC1:/home/test/test# awk '{if(NR % 3 == 0) {print $0} else {printf("%s\t", $0)}}' test.txt | sed '$ s/$/\n/' ## 因为行数不能被3整除,末尾需要用sed添加一个换行符
    01 02 03 04     05 06 07 08     09 10 11 12
    13 14 15 16     17 18 19 20     21 22 23 24
    25 26 27 28     29 30 31 32     33 34 35 36
    37 38 39 40

    其余一次类推。

  • 相关阅读:
    JavaScript高级程序设计之元素大小
    软件测试面试必备的一些基础理论概念
    golang跨平台编译
    gin shoudBind
    requests
    excelize
    gin获取全部参数
    golang随机数及pipe
    不安全代码只会在使用 /unsafe 编译的情况下出现
    MongoDB 比较运算符 $eq$gt
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/15690761.html
Copyright © 2011-2022 走看看