Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort each line in a text file

Tags:

linux

bash

I have a text file which contains on each line some words, for example:

stackoverflow coding programming
tag question badges

I must sort each line and preserve the order of lines. For example, for the above example the output should be:

coding programming stackoverflow
badges question tag

My solution until now is to create a temp file, in which all the lines are sorted. The bash script looks like this:

FILE_TMP=$FILE".tmp" 
while read line
do
echo $line | xargs -n1 | sort | xargs >>$FILE_TMP
done < $FILE

mv $FILE_TMP $FILE

It works fine, but I'm not pleased that I must create a duplicate file, especially because the files are big.

So, my question is there any solution to sort in place each line of the file?

Thank you,

like image 875
banuj Avatar asked Apr 23 '13 17:04

banuj


People also ask

How do you sort lines in a text file?

To sort lines of text files, we use the sort command in the Linux system. The sort command is used to prints the lines of its input or concatenation of all files listed in its argument list in sorted order. The operation of sorting is done based on one or more sort keys extracted from each line of input.

Can NotePad ++ sort lines?

Step 1: First to select Edit menu than select Line operation. Step 2: After select Sort Lines Lexicographically ascending.

How do you sort the entries in a text file in ascending order?

Sort a File Numerically To sort a file containing numeric data, use the -n flag with the command. By default, sort will arrange the data in ascending order. If you want to sort in descending order, reverse the arrangement using the -r option along with the -n flag in the command.


1 Answers

Try this (You may have to change the sed if file is not space separated):

cat datafile.dat | while read line; do echo $line | sed 's/ /\n/g' | sort | gawk '{line=line " " $0} END {print line}' ; done
like image 168
Eran Ben-Natan Avatar answered Sep 21 '22 23:09

Eran Ben-Natan