3

I have a text file which contains around 9999999 lines. Here I'm pasting the few lines:

1874641047  Gazipur
1874646347  Jessore
1845105653  Chittagong
1845146123  Narayanganj
1845164162  Gazipur
1843908007  Jessore

Here 1st column contains cell phone numbers & 2nd column contains regions.

I wanted to write those data in a text files region wise, as like:

Gazipur.txt:

1874641047  Gazipur
1845164162  Gazipur

Jessore.txt:

1874646347  Jessore
1843908007  Jessore

Chittagong.txt:

1845105653  Chittagong

Narayanganj.txt:

1845146123  Narayanganj

How can I do this in Linux terminal? Is there any way to do this like awk, comm, diff commands?

7

You can use awk:

awk '{print > $2".txt"}' input-file

It redirects the output to a filename made from the second field.

  • I have executed your above shared command. Here those files are conflicting which have contains same region like for Gazipur & Jessore. Its unable to create Jessore.txt or Gazipur.txt twice. Could you please test it by yourself and share me the command once again? – Rezuan Dec 22 '15 at 7:56
  • I did test it, and it worked fine for me given your sample input. It doesn't create any file twice. – muru Dec 22 '15 at 7:57
  • Okay I'll test once again & will share the testing result with screenshot. – Rezuan Dec 22 '15 at 8:38
  • @Rezuan no, please don't share a screenshot. Instead, share the exact input you used, the output you would like to see and the output you actually got. Muru's solution should work, if it doesn't, there's something strange about your data. – terdon Dec 22 '15 at 10:30
  • Okay. Thank you for your suggestion. @terdon – Rezuan Dec 22 '15 at 10:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.