Shell script: Merge rows.

Source: Internet
Author: User

Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/

There is a text:
2006
China
Sichuan
042834 1 2 3
042835 4 5 6
042836 7 8 9
2007
China
Chongqing
042837 1 2 3
042838 4 5 6
042839 7 8 9
......
......
To merge
042834 1 2 3 2006 Sichuan, China
042835 4 5 6 2006 Sichuan, China
042836 2006 Sichuan, China
042837 1 2 3 2007 Chongqing, China
042838 4 5 6 2007 Chongqing, China
042839 2007 Chongqing, China
The script is as follows:
#! /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
Run:
$./Process. Sh text
$ More result.txt
042834 1 2 3 2006 Sichuan, China
042835 4 5 6 2006 Sichuan, China
042836 2006 Sichuan, China
042837 1 2 3 2007 Chongqing, China
042838 4 5 6 2007 Chongqing, China
042839 2007 Chongqing, China
Later, a cool man used awk to complete the process:
Awk 'in in {I = 0} {If (NF! = 4) {H [I ++] = $0; next} else {I = 0; print $0 "" H [0] "H [1]" H [2]}'

Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.