I have a file with below values:

Server1,,1234,[email protected]
Server2,,1223,[email protected]
Server3,,1234,[email protected]
Server4,,1234,[email protected]

I want to split the file on the basis of email address. All the lines having email as [email protected] should come in a file named file1 and so on.

It is a very large file and I cannot hard code all the email IDs in a case statement.

  • is the input file sorted by email address? for ex, [email protected] are all next to each other?
    – Sundeep
    Apr 20, 2017 at 10:10
  • Yes the file is sorted Apr 20, 2017 at 10:36

1 Answer 1



awk -F"," '{ print $0 >> $4".csv"}' filename


-F"," -- Use "comma" field separator (FS) 
$0 -- the whole line of input
$4 -- the 4-th field of line ($NF -- the last field)
>> -- redirection operator, from `info gawk':

  This redirection prints the items into the preexisting output file
  named OUTPUT-FILE.  The difference between this and the single-'>'
  redirection is that the old contents (if any) of OUTPUT-FILE are
  not erased.  Instead, the 'awk' output is appended to the file.  If
  OUTPUT-FILE does not exist, then it is created.
  • Please explain what your awk script does.
    – tk-noodle
    Apr 20, 2017 at 11:10
  • @taifwa: in a nutshell : with "," as separator: he writes the whole line into a file named $4.csv, so as $4 is the email adress it writes each lines into the file named "email.csv" (in awj : $4 ".csv" concatenes both together, and thus print $0 is appending (>>) to a file named: $4.csv, $4 being replaced by the email@ listed on that current line). Hence all the same email adresses (ex: [email protected]) informations end up in the same file (named [email protected]). Good and simple approach (and the file doesn't even need to have the input sorted by email adresses) Apr 20, 2017 at 14:14
  • @Olivier I meant in-answer. Answers should ideally be properly fleshed out, not one-liners... the current state still does not explain how the awk script was construcuted, following what logic.
    – tk-noodle
    Apr 20, 2017 at 16:28

You must log in to answer this question.

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