-2

I want to merge two files of desired output.

File 1 example as below:

LOCATION 0 X 0
VALUE 1 2 3
VALUE 1 2 3
VALUE 1 2 3
LOCATION 1 X 0
VALUE 1 2 3
VALUE 1 2 3
VALUE 1 2 3
LOCATION 2 X 0
VALUE 1 2 3
VALUE 1 2 3
VALUE 1 2 3

File 2 example as below:

LOCATION 0 X 0
VALUE 4 5 6
VALUE 4 5 6
VALUE 4 5 6
VALUE 4 5 6
LOCATION 1 X 0
VALUE 4 5 6
VALUE 4 5 6
VALUE 4 5 6
VALUE 4 5 6
LOCATION 2 X 0
VALUE 4 5 6
VALUE 4 5 6
VALUE 4 5 6
VALUE 4 5 6

The desired output is below:

LOCATION 0 X 0
VALUE 1 2 3
VALUE 1 2 3
VALUE 1 2 3
VALUE 4 5 6
VALUE 4 5 6
VALUE 4 5 6
VALUE 4 5 6
LOCATION 1 X 0
VALUE 1 2 3
VALUE 1 2 3
VALUE 1 2 3
VALUE 4 5 6
VALUE 4 5 6
VALUE 4 5 6
VALUE 4 5 6
LOCATION 2 X 0
VALUE 1 2 3
VALUE 1 2 3
VALUE 1 2 3
VALUE 4 5 6
VALUE 4 5 6
VALUE 4 5 6
VALUE 4 5 6

As you can see the only common is "LOCATION * " by which the rows needs to be vertically sorted.

1

With GNU awk this does the job in my tests:

awk 'BEGIN{RS="LOCATION [0-9] X [0-9]"}NR==FNR{f1[RT]=$0;next} \
RT in f1{printf("%s%s%s", f1[RT],gensub("\n","",1,$0),RT)}' file1 file2

Testing:

$ cat file1
LOCATION 0 X 0
VALUE 1a 2 3
VALUE 1b 2 3
VALUE 1c 2 3
LOCATION 1 X 0
VALUE 1d 2 3
VALUE 1e 2 3
VALUE 1f 2 3
LOCATION 2 X 0
VALUE 1g 2 3
VALUE 1h 2 3
VALUE 1i 2 3

$ cat file2
LOCATION 0 X 0
VALUE 4a 5 6
VALUE 4b 5 6
VALUE 4c 5 6
VALUE 4d 5 6
LOCATION 1 X 0
VALUE 4e 5 6
VALUE 4f 5 6
VALUE 4g 5 6
VALUE 4h 5 6
LOCATION 2 X 0
VALUE 4i 5 6
VALUE 4j 5 6
VALUE 4k 5 6
VALUE 4l 5 6

$ awk 'BEGIN{RS="LOCATION [0-9] X [0-9]"}NR==FNR{f1[RT]=$0;next}RT in f1{printf("%s%s%s", f1[RT],gensub("\n","",1,$0),RT)}' file1 file2
LOCATION 0 X 0
VALUE 1a 2 3
VALUE 1b 2 3
VALUE 1c 2 3
VALUE 4a 5 6
VALUE 4b 5 6
VALUE 4c 5 6
VALUE 4d 5 6
LOCATION 1 X 0
VALUE 1d 2 3
VALUE 1e 2 3
VALUE 1f 2 3
VALUE 4e 5 6
VALUE 4f 5 6
VALUE 4g 5 6
VALUE 4h 5 6
LOCATION 2 X 0
VALUE 1g 2 3
VALUE 1h 2 3
VALUE 1i 2 3
VALUE 4i 5 6
VALUE 4j 5 6
VALUE 4k 5 6
VALUE 4l 5 6
  • @user222282 Did this solution worked for you like my tests? – George Vasiliou Mar 23 '17 at 8:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.