2

I have a file that I would like to break up into multiple files with uniq values for the first column. For example, here is a file:

fileA.txt

1    Cat
1    Dog
1    Frog
2    Boy
2    Girl
3    Tree
3    Leaf
3    Branch
3    Trunk

I would like my output to look something like this:

file1.txt

1    Cat
2    Boy
3    Tree

file2.txt

1    Dog
2    Girl
3    Leaf

file3.txt

1    Frog
3    Branch

file4.txt

3    Trunk

If a value does not exist, I want it to be skipped. I have tried to search for similar situations to mine, but I've come up short. Does anyone have idea of how to do this?

Edit: My awk version is: awk version 20070501

1 Answer 1

4
$ gawk '{print > "file" ++a[$1] ".txt"}' input

# And on OSX awk, and also gawk:

$ awk '{print > ("file" ++a[$1] ".txt")}' input


$ head file*txt
==> file1.txt <==
1    Cat
2    Boy
3    Tree

==> file2.txt <==
1    Dog
2    Girl
3    Leaf

==> file3.txt <==
1    Frog
3    Branch

==> file4.txt <==
3    Trunk

edit: An explanation. This prints the current line into (>) fileX.txt. Every time the first field is found, an array a[$1] is increased by 1 before it is evaluated. This is used to establish the file name.

edit 2: I do not have the possibility to check with OSX awk, but I guess if you are halfly serious about using awk, you would do good installing gawk or mawk. You could, however, give this a shot:

$ awk '{a[$1]++; f = "file" a[$1] ".txt"; print > f}' input

This does the same, but all the action is split in separate steps. This is to help OSX awk to understand the right order of evaluating the parts.

7
  • When I attempted this solution, I got this error awk: syntax error at source line 1 context is {print > >>> "file"++ <<< The actual column in my file that I am sorting by is column 6. Therefore I changed the array to a[$6]. Was this incorrect? Feb 2, 2016 at 15:57
  • I changed the answer a bit, and added some spacing. Make sure there is a space between "file" and ++a[$6], and that there is no space between ++ and a[$6]. If that does not work, please reveal what awk --version says.
    – joepd
    Feb 2, 2016 at 16:01
  • I'm still getting the same error.. I've edited my original post with my awk version. Feb 2, 2016 at 16:10
  • The most important question is, what kind of awk. According to Wikipedia, these are the implementations: BWK, gawk, mawk, awka, tawk, Jawk, jawk, xgawk, QSEAWK, BusyBox
    – joepd
    Feb 2, 2016 at 16:19
  • I use awk for most of my needs. However, this does not seem to work. Very disappointing. I think it has something to do with me being on a mac :( Feb 2, 2016 at 18:55

You must log in to answer this question.

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