[英]bash - how do you sort within the lines of a text file
Using the linux command sort
, how do you sort the lines within a text file?使用 linux 命令
sort
,如何对文本文件中的行进行排序?
Normal sort
swaps the lines until they're sorted while I want to swap the words within the lines until they're sorted.正常
sort
交换行直到它们被排序,而我想交换行中的单词直到它们被排序。
Example:例子:
Input.txt输入.txt
z y x v t
c b a
Output.txt输出.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.要使用
sort
行内的单词进行sort
,您需要逐行阅读,并为每行调用一次sort
。 It gets quite tricky though, and in any case, running one sort
process for each line wouldn't be very efficient.尽管如此,它变得相当棘手,无论如何,为每一行运行一个
sort
过程不会非常有效。
You could do better by using Perl (thanks @glenn-jackman for the awesome tip!):使用 Perl 可以做得更好(感谢@glenn-jackman的精彩提示!):
perl -lape '$_ = qq/@{[sort @F]}/' file
If you have gnu awk
then it can be done in a single command using asort
function :如果您有
gnu awk
则可以使用asort
函数在单个命令中完成:
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
):这是一种实际使用 linux
sort
命令(加上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.现在,这提出了几个假设(可能并不总是正确的),但主要思想是
xargs -n1
获取一行中的所有标记,并在 stdout 中的单独行上发出它们。 This output gets piped through sort
and then a final xargs
with no arguments puts them all back into a single line.此输出通过
sort
进行管道传输,然后没有参数的最终xargs
将它们全部放回一行。
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:这有点尴尬,但这仅使用了一个基本的
sort
命令,因此它可能比需要 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.包含
echo
以插入换行符,默认情况下printf
不包含该换行符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.