1

I have a data like this

15 23
16 23
17 24
18 24

I want to combine/group the data in the first column by the data in the last column:

15 16 23
17 18 24

How to do it with awk?

0

3 Answers 3

3

WIth awk:

awk '{ seen[$2]= seen[$2]? seen[$2]FS$1:$1 } 
    END{ for (x in seen) print seen[x], x }' infile
15 16 23
17 18 24

Here we are using array seen with the key of column $2 and value from column $1. if the key $2 was the same for each values, then append that value to the end of its previous value in array, and at the END print final value first then its key.

The Ternary condition is used to check if for that key there was value in array before, if so, then append the new value to the end of the exiting value with default Field Seperator FS between; else just add that value as first value.

0
awk '{AA[$2]=AA[$2]" "$1}END{for(i in AA){print AA[i]" "i}}' datafile.txt
3
  • this will add single space before start of each line. Sep 5, 2018 at 8:52
  • Yes, I know, but what I do not know: if the result has to be sorted, how many coincidence we can expext, if the result has to include unique X value etc. The first space can be cleared wih sed and for lot of conseqent process it doe no problem ;-) (If I specify this homework I asked the X to be the first on the line)
    – schweik
    Sep 5, 2018 at 9:01
  • Wrap the output in substr to strip the leading space character. For example awk 'BEGIN {print substr("abcde",2)}' will output bcde. Sep 5, 2018 at 10:51
0
sed -Ee '
   :join
      $!N
      s/(\s\S+)\n(.*\1)$/ \2/
   tjoin
   P;D
'  input.txt

Explanation:

  1. Keep two lines in the pattern space.
  2. Try to join the lines by looking at the last fields of the two lines in pattern space.
  3. Repeat this joining procedure while the last fields are same.
  4. Then when they differ, print the first portion, which by that time holds the 1st fields of all the prior lines, space separated, & the common last field. Remove this portion, then go back for more.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .