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,
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.
Step 1: First to select Edit menu than select Line operation. Step 2: After select Sort Lines Lexicographically ascending.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With