【问题标题】:Sorting words in lines in a file and output sorted lines again对文件中的行中的单词进行排序并再次输出排序的行
【发布时间】:2011-04-03 21:24:29
【问题描述】:

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

例如:

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

我希望输出是:

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

我似乎无法通过命令行使其工作

我可能忽略了一些事情

【问题讨论】:

    标签: macos bash sorting command-line awk


    【解决方案1】:

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

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

    【讨论】:

    • 您可以(并且应该)嵌套$(),并且不要使用反引号。
    【解决方案2】:

    仅使用 awk:

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

    【讨论】:

      【解决方案3】:

      这对我有用:

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

      这个想法是:

      • 逐行读取文件
      • 每读取一行,替换空格 带换行符
      • 对结果列表进行排序
      • 用空格替换换行符和
      • 打印

      【讨论】:

        【解决方案4】:

        如果你安装了 perl:

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

        前:

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

        【讨论】:

        • 我认为像 perl 这样的语言非常有价值,值得安装它并理解该解决方案。使 perl(或某种此类语言)变得非常必要并不需要太多额外的复杂性。
        • 最好是split ' ',以防出现空格。
        • 你不需要cat。就做perl -ne 'blah blah' &lt; input.txt &gt; output.txt
        猜你喜欢
        • 2017-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多