zoukankan      html  css  js  c++  java
  • 【Shell脚本】合并行

    作者:gnuhpc
    出处:http://www.cnblogs.com/gnuhpc/

    有一个文本:
    2006
    中国
    四川
    042834 1 2 3
    042835 4 5 6
    042836 7 8 9
    2007
    中国
    重庆
    042837 1 2 3
    042838 4 5 6
    042839 7 8 9
    ......
    ......
    要合并为
    042834 1 2 3 2006 中国 四川
    042835 4 5 6 2006 中国 四川
    042836 7 8 9 2006 中国 四川
    042837 1 2 3 2007 中国 重庆
    042838 4 5 6 2007 中国 重庆
    042839 7 8 9 2007 中国 重庆
    脚本如下:
    #!/bin/bash
    #########################################################################
    # Author: pchuang@cn.ibm.com
    # Created Time: Sun 05 Apr 2009 10:04:51 AM CST
    # File Name: process.sh
    # Description: A script for the processing of the TEXT
    #########################################################################
    file=$1
    i=1
    lines[0]=""
    if [ ! -s $1 ] ; then
    echo "Please specify a valid text file"
    exit 1
    fi
    while read line
    do
    lines[$i]="$line"
    if [ $i -eq 6 ] ; then
    lines[$i]="$line"
    for j in $(seq 4 6); do
    echo ${lines[$j]} ${lines[1]} ${lines[2]} ${lines[3]} >> result.txt
    done
    let i=0
    fi
    let i=$i+1
    done < $1
    执行:
    $./process.sh text
    $more result.txt
    042834 1 2 3 2006 中国 四川
    042835 4 5 6 2006 中国 四川
    042836 7 8 9 2006 中国 四川
    042837 1 2 3 2007 中国 重庆
    042838 4 5 6 2007 中国 重庆
    042839 7 8 9 2007 中国 重庆
    后来某牛人用AWK也完成了:
    awk 'BEGIN{i=0}{if(NF!=4){h[i++]=$0;next}else{i=0;print $0" "h[0]" "h[1]" "h[2]}}'

    作者:gnuhpc
    出处:http://www.cnblogs.com/gnuhpc/


                   作者:gnuhpc
                   出处:http://www.cnblogs.com/gnuhpc/
                   除非另有声明,本网站采用知识共享“署名 2.5 中国大陆”许可协议授权。


    分享到:

  • 相关阅读:
    19.SimLogin_case07
    19.SimLogin_case06
    19.SimLogin_case05
    19.SimLogin_case04
    19.SimLogin_case03
    闲说性能测试
    iostat命令详解
    Linux vmstat命令实战详解
    RAC集群节点故障模拟测试
    Oracle RAC功能测试
  • 原文地址:https://www.cnblogs.com/gnuhpc/p/2810114.html
Copyright © 2011-2022 走看看