Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sort a file based on column in another file 1

Status
Not open for further replies.

blarneyme

MIS
Jun 22, 2009
160
US
File1:
boston:1:x:
chicago:1:x:
baltimore:1:x:
buffalo:1:x:
denver:1:x:
reno:1:x:
dallas:1:x:
austin:1:x:

File2:
chicago:1:x:
baltimore:1:x:
austin:1:x:
dallas:1:x:
buffalo:1:x:
boston:1:x:
denver:1:x:
reno:1:x:

File2 should be sorted identically to File1. I know how to sort a single file, but how to sort a file based on the field in another file I am uncertain.

Thanks.
 
Hi

For small files you can use a pure AWK solution :
Code:
awk -F: -vOFS=: 'FNR==NR{o[$1]=NR;next}{l[o[$1]]=$0}END{for(i=1;i in l;i++)print l[i]}' /input/file1 /input/file2 > /output/file
But for big files is better to let [tt]sort[/tt] handle it. Use AWK to prefix the lines, to get the desired order :
Code:
awk -F: -vOFS=: 'FNR==NR{o[$1]=NR;next}{$1=o[$1]" "$1}1' /input/file1 /input/file2 | sort -n | cut -d' ' -f2- > /output/file
Tested with [tt]gawk[/tt] and [tt]mawk[/tt].


Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top