Sunday, May 5, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 2243  / 2 Years ago, fri, march 4, 2022, 12:27:03

I need to sort the lines of a text file (without any extension) where the lines are separated by %. When using sort command, those %s are also getting sorted out which I do not want.



How to sort the text file from command line or by any other method and save with same name?



For example:



filename: myfile



Before sorting>>



A line one
%
C line two
%
B line three
%


After sorting>>



%
%
%
A line one
B line three
C line two


Desired>>



A line one
%
B line three
%
C line two
%

More From » text

 Answers
6

I would strip out the separator (awk is looking for odd lines), sort it into a temporary file (see comments) and then sed that file to add the separator back.



awk 'NR%2==1' myfile | sort -o tmpfile; sed -r 's/$/
%/g' tmpfile


That just outputs to stdout so stick a > myfile on the end of it if you want it to pipe that back into your file. I've left it bare so you can test it.



Sidebar: There are about a hundred different ways of handling the reinsertion of the separators. These would all work:



awk '{print $0"
%"}'
while read line; do echo -e "$line
%"; done
xargs -i^ echo -e "^
%" # won't work with a redirection >

[#30504] Friday, March 4, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nstitutencert

Total Points: 171
Total Questions: 126
Total Answers: 124

Location: Azerbaijan
Member since Fri, May 12, 2023
1 Year ago
;