# simple code to collapse rows in bash

**URL:** <https://community.unix.com/t/simple-code-to-collapse-rows-in-bash/315612>\
**Category:** UNIX for Dummies Questions & Answers\
**Created:** [August 23, 2012, 1:18pm UTC](https://community.unix.com/t/simple-code-to-collapse-rows-in-bash/315612 "2012-08-23T13:18:08Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![torchij](https://community.unix.com/letter_avatar/torchij/32/5_5575768a8748004e209b776fc1b2916d.png) [@torchij](https://community.unix.com/u/torchij)\
**Post date:** [August 23, 2012, 1:18pm UTC](https://community.unix.com/t/simple-code-to-collapse-rows-in-bash/315612/1 "2012-08-23T13:18:08Z")

</div>

Hello to the experts! I have a file that I'd like to collapse based on a common ID column, separated by a character delimiter.  
example input

```nohighlight
a 1 6 word1 uniq1
b 2 7 WORD2 uniq2
b 2 7 WORD2 uniq3
b 2 7 WORD2 uniq4
c 3 8 word4 uniq5
d 4 9 word5 uniq6
e 5 1 word6 uniq7

```

desired output

```nohighlight
a 1 6 word1 uniq1
b 2 7 WORD2 uniq2;uniq3;uniq4
c 3 8 word4 uniq5
d 4 9 word5 uniq6
e 5 1 word6 uniq7

```

Note that column 4 contains the ID used to collapse, and column 5 are the strings to actually collapse with the delimter ";"  
Help is sincerely appreciated!  
Many thanks.

---

<div class="post-metadata">

**Author:** ![vgersh99](https://community.unix.com/user_avatar/community.unix.com/vgersh99/32/14851_2.png) [@vgersh99](https://community.unix.com/u/vgersh99)\
**Post date:** [August 23, 2012, 1:33pm UTC](https://community.unix.com/t/simple-code-to-collapse-rows-in-bash/315612/2 "2012-08-23T13:33:09Z")

</div>

```nohighlight
awk '{idx=$1 OFS $2 OFS $3 OFS $4}{a[idx]=(idx in a)?a[idx]";"$NF:$NF}END{for(i in a) print i,a}' myFile

```

---

<div class="post-metadata">

**Author:** ![torchij](https://community.unix.com/letter_avatar/torchij/32/5_5575768a8748004e209b776fc1b2916d.png) [@torchij](https://community.unix.com/u/torchij)\
**Post date:** [August 23, 2012, 2:18pm UTC](https://community.unix.com/t/simple-code-to-collapse-rows-in-bash/315612/3 "2012-08-23T14:18:00Z")

</div>

vgersh99, thank you so much that works exactly as I wanted. Is it easily adaptable to choose any two columns, one as the ID column as one as the column to collapse?  
Thank you.

---

<div class="post-metadata">

**Author:** ![vgersh99](https://community.unix.com/user_avatar/community.unix.com/vgersh99/32/14851_2.png) [@vgersh99](https://community.unix.com/u/vgersh99)\
**Post date:** [August 23, 2012, 2:51pm UTC](https://community.unix.com/t/simple-code-to-collapse-rows-in-bash/315612/4 "2012-08-23T14:51:01Z")

</div>

you'll need to change the code for the 'idx' - right now I' taking columns/fields 1,2,3, and 4 as the unique key to 'merge/collapse' on.
