【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/

转载于:https://www.cnblogs.com/gnuhpc/archive/2012/12/09/2810114.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值