Sorry for the confusion.
Let’s start from the beginning.
I have two text files: Haruki.txt and Premchand.txt
Here, I would explain by taking two scenarios in mind:
- You want to merge the text data of both files and then sort the output
- You want to have sorted output of both files but without mixing the text
So let’s start with the first scenario.
- If you have two text files that have similar data and now you want to merge them in alphabetical order. all you have to do is use the
-n
flag with the desired amount of lines and append the filenames and in the end, you have to pipe your input to the sort command.
For example, if I want to merge two text files Haruki.txt
and Premchand.txt
for the first 5 lines in alphabetical order, I will be using the following:
head -q -n 5 Premchand.txt Haruki.txt | sort
Here’s the output:
sagar@itsFOSS:~$ head -q -n 5 Premchand.txt Haruki.txt | sort
A Wild Sheep Chase (1982)
Godan
Hard-Boiled Wonderland and the End of the World (1985)
Hear the Wind Sing (1979)
Karmabhoomi
Nirmala
Norwegian Wood (1987)
Pinball, 1973 (1980)
Rangbhoomi
Sevasadan
Remember, this will mix the text files and then sort them so the output order will only be alphabetical and not specific to a file.
Now, let’s have a look at the second scenario.
- If you want to use multiple files and sort the first 5 lines of each file but without mixing the output such as the first 5 lines should only be from the first text file so here’s how you do it.
Here, I will be using the same text files to make things easy:
head -q -n 5 Premchand.txt | sort && head -n 5 -q Haruki.txt | sort
Here, you’d see, I have used the &&
operator which will execute the first part of the command first and then will proceed to the second one.
And here’s the expected output:
sagar@itsFOSS:~$ head -q -n 5 Premchand.txt | sort && head -n 5 -q Haruki.txt | sort
Godan
Karmabhoomi
Nirmala
Rangbhoomi
Sevasadan
A Wild Sheep Chase (1982)
Hard-Boiled Wonderland and the End of the World (1985)
Hear the Wind Sing (1979)
Norwegian Wood (1987)
Pinball, 1973 (1980)
Pretty simple. Isn’t it?