Whenever you need to work with lists that are stored as text files on Linux– specifically long ones– you can take advantage of some simple commands to make manipulating them a lot easier. Any text file can be quickly arranged, however you can likewise arbitrarily set up the lines, number them or sign up with files when 2 share an initial common field. In fact, if you only want to see every other line or every fifth line in a file, you can do that too. This post goes through the commands to do all of these things.Sorting files The sort command makes sorting text files extremely easy. To view the contents of a text file in arranged order, all you need to do is type a command like this: $sort myfile If you wish to conserve the output or add it to
the bottom of another file, one of the commands below will do that for you.$sort myfile > sortedfile $sort myfile >> otherfile Once you add lines to an existing file as shown in the
2nd command above, you may need to arrange it again. The commands listed below would do that for you and will guarantee that the file has the initial name.$sort otherfile > otherfile.new$ mv otherfile.new otherfile The sort command likewise has quite a few choices. For example, if you have a file
with dates in alphabetic order, you could change to showing it in annual date order with the-M choice in the command on the ideal listed below:$cat birthdays$sort-M birthdays Jan 4, 1972 Jan 4, 1972 Mar 18, 1949 Jan 8, 1954 May 1, 1976
Mar 18, 1949 Jan 8, 1954 Might 1, 1976 Sep 23, 1979 Aug 6, 1956 Aug 6, 1956 Sep 23, 1979 To arrange a long list of colors and show them in columns, use a command like this one:$sort colors|column Aqua Brown Gold Navy blue Purple Tomato Yellow Azure Chocolate Green Navy blue Red Blue-green Black Cyan Grey Olive Salmon Violet Blue Cyan Lime Orange Sİlver Wheat Bronze Dark blue Maroon Pink Teal White Shuffling lines To arbitrarily arrange the lines in a text file, use the shuf(shuffle)command. For instance, if you want to shuffle a list of good friends each month to randomly pick who to take out to lunch, you might utilize a command like this:$shuf pals|head -2 Sam Patty Run the command a couple of times in a row and you ought to get a different listing each time. Sorting by number or
text If you wish to arrange the lines of a file numerically(assuming they are not listed numerically to begin with), use the sort-n choice. Keep in mind
, however, that any lines that don’t start with a number will appear first$sort -n story|head -5 1 As soon as upon a time 2 There was a Linux fairy 3 who liked to surprise 4 users by introducing 5 brand-new commands. Displaying every Nth line from a text file The awk command provides a method to view every other, third, fourth or Nth line in a file by utilizing an NR(record number) argument as shown in the commands listed below. The first command ensures that only the 2nd, fourth
, sixth, etc lines are displayed. The second would display every 7th line. Think of … Source