对文件中的行中的单词进行排序并再次输出排序后的行

发布于 2024-09-16 03:52:05 字数 301 浏览 7 评论 0原文

我想对文件中的行上的单词逐行进行排序,并且我希望输出是按字母顺序排序的单词的行。

例如:

queue list word letter gum  
another line of example words  
...

我希望输出为:

gum letter list queue word  
another example line of words  
...  

我似乎无法通过命令行让它工作

我可能忽略了一些事情

I want to sort the words on lines in a file line by line and I want the ouptut to be lines with the words sorted alphabetically.

for example:

queue list word letter gum  
another line of example words  
...

I want the output to be:

gum letter list queue word  
another example line of words  
...  

I can't seem to get it to work via commandline

I'm overlooking things probably

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

戈亓 2024-09-23 03:52:05

如果你安装了 perl:

perl -ne 'print join " ", sort split /\s/ ; print "\n"'

EX:

cat input | perl -ne 'print join " ", sort split /\s/ ; print "\n"' > output

If you have perl installed:

perl -ne 'print join " ", sort split /\s/ ; print "\n"'

EX:

cat input | perl -ne 'print join " ", sort split /\s/ ; print "\n"' > output
自演自醉 2024-09-23 03:52:05

如果包含单词列表的文件是 foo.txt

while read line; do
  echo $(for w in $(echo "$line"); do echo "$w"; done |sort);
done < foo.txt

If the file with the list of words is foo.txt:

while read line; do
  echo $(for w in $(echo "$line"); do echo "$w"; done |sort);
done < foo.txt
丶视觉 2024-09-23 03:52:05

这对我有用:

while read line
do
echo $line | tr " " "\n" | sort | tr "\n" " " ;echo
done < "input"

想法是:

  • 逐行读取文件,
  • 每行读取,替换空格
    使用换行符
  • 排序结果列表
  • 用空格替换换行符并
  • 打印

This works for me:

while read line
do
echo $line | tr " " "\n" | sort | tr "\n" " " ;echo
done < "input"

The idea is to:

  • read the file line by line
  • for each line read, replace space
    with newline
  • sort the resultant list
  • replace newline with space and
  • print
千紇 2024-09-23 03:52:05

仅使用 awk:

gawk '{
    split($0, a)
    asort(a)
    for (i=1; i<=NF; i++) printf("%s ", a[i])
    print ""
}' infile

With awk only:

gawk '{
    split($0, a)
    asort(a)
    for (i=1; i<=NF; i++) printf("%s ", a[i])
    print ""
}' infile
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文