Using the linux command sort
, how do you sort the lines within a text file?
Normal sort
swaps the lines until they're sorted while I want to swap the words within the lines until they're sorted.
Example:
Input.txt
z y x v t
c b a
Output.txt
t v x y z
a b c
To sort words within lines using sort
, you would need to read line by line, and call sort
once for each line. It gets quite tricky though, and in any case, running one sort
process for each line wouldn't be very efficient.
You could do better by using Perl (thanks @glenn-jackman for the awesome tip!):
perl -lape '$_ = qq/@{[sort @F]}/' file
If you have gnu awk
then it can be done in a single command using asort
function :
awk '{for(i=1; i<=NF; i++) c[i]=$i; n=asort(c);
for (i=1; i<=n; i++) printf "%s%s", c[i], (i<n?OFS:RS); delete c}' file
t v x y z
a b c
Here's a fun way that actually uses the linux sort
command (plus xargs
):
while read line; do xargs -n1 <<< $line | sort | xargs; done < input.txt
Now, this makes several assumptions (which are probably not always true), but the main idea is xargs -n1
takes all the tokens in a line and emits them on separate lines in stdout. This output gets piped through sort
and then a final xargs
with no arguments puts them all back into a single line.
I was looking for a magic switch but found my own solution more intuitive:
$ line="102 103 101 102 101"
$ echo $(echo "${line}"|sed 's/\W\+/\n/g'|sort -un)
101 102 103
Thank you!
It's a little awkward, but this uses only a basic sort
command, so it's perhaps a little more portable than something that requires GNU sort:
while read -r -a line; do
printf "%s " $(sort <<<"$(printf '%s\n' "${line[@]}")")
echo
done < input.txt
The echo
is included to insert a newline, which printf
doesn't include by default.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.