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
?
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.
awk '{AA[$2]=AA[$2]" "$1}END{for(i in AA){print AA[i]" "i}}' datafile.txt
awk 'BEGIN {print substr("abcde",2)}'
will output bcde
.
Sep 5, 2018 at 10:51
sed -Ee '
:join
$!N
s/(\s\S+)\n(.*\1)$/ \2/
tjoin
P;D
' input.txt
Explanation: