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

posted @ 2012-12-09 15:43  gnuhpc  阅读(1799)  评论(0编辑  收藏  举报