Sheldon
Sheldon

Reputation: 179

bash: how to add header to its corresponding lines

i have a file which looks like below, and i want to add header to its corresponding lines ONLY in my shell script..

CGRT,630,SC063P1
10001,X,6849
10003,X,6913
10005,X,6977
10007,X,7041
10037,X,7105
10039,X,7169
CGRT,631,SC063P2
10049,X,8481
10051,X,8545
10077,X,6721
10079,X,6785
10081,X,1185
CGRT,632,SC063P3
10110,X,1601
10111,X,1633
10112,X,1665
10113,X,1953
10114,X,1985

required output will be like below..

CGRT,630,SC063P1    10001,X,6849
CGRT,630,SC063P1    10003,X,6913
CGRT,630,SC063P1    10005,X,6977
CGRT,630,SC063P1    10007,X,7041
CGRT,630,SC063P1    10037,X,7105
CGRT,630,SC063P1    10039,X,7169
CGRT,631,SC063P2    10049,X,8481
CGRT,631,SC063P2    10051,X,8545
CGRT,631,SC063P2    10077,X,6721
CGRT,631,SC063P2    10079,X,6785
CGRT,631,SC063P2    10081,X,1185
CGRT,632,SC063P3    10110,X,1601
CGRT,632,SC063P3    10111,X,1633
CGRT,632,SC063P3    10112,X,1665
CGRT,632,SC063P3    10113,X,1953
CGRT,632,SC063P3    10114,X,1985

i have already tried using awk & sed command but no luck. Please help.

Upvotes: 0

Views: 277

Answers (3)

Akshay Hegde
Akshay Hegde

Reputation: 16997

Using awk:

awk '!/^[0-9]/{h=$0;next}{print h,$0}' infile

Upvotes: 3

RavinderSingh13
RavinderSingh13

Reputation: 133508

Following awk may also help you in same.

awk '/^[a-zA-Z]/{val=$0;next} {print val "\t" $0}'  Input_file

Output will be as follows.

CGRT,630,SC063P1        10001,X,6849
CGRT,630,SC063P1        10003,X,6913
CGRT,630,SC063P1        10005,X,6977
CGRT,630,SC063P1        10007,X,7041
CGRT,630,SC063P1        10037,X,7105
CGRT,630,SC063P1        10039,X,7169
CGRT,631,SC063P2        10049,X,8481
CGRT,631,SC063P2        10051,X,8545
CGRT,631,SC063P2        10077,X,6721
CGRT,631,SC063P2        10079,X,6785
CGRT,631,SC063P2        10081,X,1185
CGRT,632,SC063P3        10110,X,1601
CGRT,632,SC063P3        10111,X,1633
CGRT,632,SC063P3        10112,X,1665
CGRT,632,SC063P3        10113,X,1953
CGRT,632,SC063P3        10114,X,1985

Upvotes: 1

potong
potong

Reputation: 58391

This might work for you (GNU sed):

sed '/^[^0-9]/h;//d;G;s/\(.*\)\n\(.*\)/\2 \1/' file

If it is a header, store and then delete the line. Otherwise, append the stored line and then swap the lines around.

Upvotes: 1

Related Questions