1

I have a series of txt files, each with numerous entries. I usually merge all the txt files into one output file using cat, however it becomes a little bit messy because I cannot be sure from which original txt file it came from.

I was wondering if there is a way, using the command line, to first merge all the txt files in alphabetical order and at the same time add the suffix to the original entry to note the file it came from.

For example, let's say I have 2 txt files, each with three entries:

File_One:

  Alpha
  Bravo 
  Charlie

File_Two:

  Alpha
  Bravo
  Delta

What I would like to do is this:

  1. Merge the two lists in one output txt file sorted in alphabetical order;
  2. Add the suffix to show from which list it comes from:

       Alpha_File_One
       Alpha_File_Two
       Bravo_File_One
       Bravo_File_Two
       Charlie_File_One
       Delta_File_Two
    

Is this possible?

4
  • Use code formatting to format your sample input files and output exactly as they should appear, please. – muru Oct 12 '15 at 0:50
  • Sorry muru not sure what you are asking (i am not a cli expert), but that is how i would like to it be in the output file. – simple mind Oct 12 '15 at 0:53
  • I am not talking about the CLI. I'm talking about formatting the question. See askubuntu.com/editing-help#code. Do your files have semicolons, for example? – muru Oct 12 '15 at 0:55
  • Ok, got you. Made the corrections to my question. – simple mind Oct 12 '15 at 1:01
5

As Florian says, you should first add the filename and then sort. Another method is to use awk:

$ awk '{printf "%s_%s\n", $0, FILENAME}' f1 f2 | sort
Alpha_f1
Alpha_f2
Bravo_f1
Bravo_f2
Charlie_f1
Delta_f2

printf prints arguments in a specified format, %s_%s\n meaning two strings separated by _ and followed by a newline. $0 and FILENAME contain the current line and filename respectively. I have named the files f1 and f2, in this example.

0
2

You need to do it the other way around: First add the suffix, den merge and sort:

(sed 's/$/_File_One/' File_One; sed 's/$/_File_Two/' File_Two) | sort 
0

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.