0

I execute the following code :

for i in {1..12};do  printf "%s %s\n" "${edate1[$i]}" "${etime1[$i]}"

(I retrieve the values of edate1 and etime1 from my database and store it in an array which works fine.)

I receive the o/p as:

97 16
97 16
97 12
107 16
97 16
97 16
97 16
97 16
97 16
97 16
97 16
100 15

I need to sort the first column using the sort command.

Expected o/p:

107 16
100 16
97 12
97 16
97 16
97 16
97 16
97 16
97 16
97 16
97 16
97 15
4
  • 1
    So... how does 97 12 get to come before 97 16, but 97 15 has to come last? Your samples make no sense. Hint: look into the -n option for sort. Commented Jul 11, 2012 at 0:16
  • o/p is displayed as vertical columns. Commented Jul 11, 2012 at 0:16
  • sorting only the first column.second one remains the same thats why you see second column in random order. Commented Jul 11, 2012 at 0:21
  • @khachik The original poster wants to leave the second column in place. Your solution doesn't achieve this, because your solution leaves each line intact. The original poster seems to be saying that the second column is in the exact order as it appears in the input... it's only the values in the first column that are reverse sorted. In other words, in the final solution, most lines will normally be "torn". Commented Jul 11, 2012 at 0:40

2 Answers 2

2

This is what I did to find your solution:

  1. Copy your original input to in.txt

  2. Run this code, which uses awk, sort, and paste.

awk '{print $1}' in.txt | sort -g -r -s > tmp.txt
paste tmp.txt in.txt | awk '{print $1 " " $3}' > out.txt

Then out.txt matches the expected output in your original post.

To see how it works, look at this:

$ paste tmp.txt in.txt
107     97 16
100     97 16
97      97 12
97      107 16
97      97 16
97      97 16
97      97 16
97      97 16
97      97 16
97      97 16
97      97 16
97      100 15

So you're getting the first column sorted, then the original columns in place. Awk makes it easy to print out the columns (fields) you're interested in, ie, the first and third.

Sign up to request clarification or add additional context in comments.

Comments

1

This is the best and simplest way to sort your data

<OUTPUT> | sort -nrk1

Refer the following link to know more about the magic of sort.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.