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

    其余一次类推。

  • 相关阅读:
    TLS Version 1.0 Protocol Detection 漏洞修复
    更新ESXI版本
    CentOS7禁止PING的方法
    Nginx_ingress配置ssl_dhparam
    Nessus安装与使用
    centos7的防火墙不能控制docker容器端口的问题
    centos 7 安装mariadb
    CentOS7 ICMP漏洞修复
    如何基于LSMtree架构实现一写多读
    vitual box 安装centos7
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/15690761.html
Copyright © 2011-2022 走看看