【问题标题】:Bash convert file to lowercase and sortBash将文件转换为小写并排序
【发布时间】:2015-04-07 00:44:53
【问题描述】:

我正在尝试编写一个脚本,它将接收inputFile,将其转换为小写,对其进行排序,然后将结果存储回原始文件中。我对 bash 很陌生,所以这是我迄今为止提出的解决方案:

awk '{ print tolower($0) }' $inputFile

index=0
for i in `cat $inputFile`
do                   
    tables[${index}]=$i
    index=$(($index + 1))
done

IFS=$'\n' tables=($(sort <<<"${tables[*]}"))
rm -r $inputFile
printf "%s\n" "${tables[@]}" >> $inputFile

这个排序方面工作得很好,但我无法将awk 的结果存储到原始inputFile,所以排序后的表仍然包含大写字母。我尝试将awk 的输出重定向到&gt; inputFile,但这也不起作用。

样本inputFile:

TABLE.thisisaTABLE
taBLe.hellO
HELLO.table
hi.table

想要的输出(回到原来的inputFile):

hello.table
hi.table
table.hello
table.thisisatable

【问题讨论】:

  • 它看起来很有趣,几乎没有什么需要改进的地方(while read line; do ... done &lt; file 优于 for i in cat...)。您能否指出具有所需输出的示例输入文件?
  • IFS 的用法不是该行本地的。
  • @fedorqui 我已经更新了 OP 以包含信息。
  • 你的目标是什么版本的 bash?
  • 为什么不只是awk '{ print tolower($0) }' $inputFile | sort -o $inputFile?您在排序时是否希望进行其他处理?

标签: bash sorting awk lowercase ifs


【解决方案1】:

你可以使用 Perl:

$ perl -lne 'push @a, lc; END { print join("\n", sort @a) }' $inputFile
hello.table
hi.table
table.hello
table.thisisatable

作品:

perl -lne      # invoke perl with a loop around the lines of the file
push @a, lc;   # make line read lower case; push the result
END            # block of code executed at the end
{ print join("\n", sort @a) }   # Print each sorted line with \n 

如果你想就地修改文件:

$ perl -i.bak -0777 -lne 'print join("\n", sort map(lc, split /\n/))' file.txt

如果您不想制作备份文件:

$ perl -i -0777 -lne 'print join("\n", sort map(lc, split /\n/))' file.txt

【讨论】:

    【解决方案2】:

    sed 的类似解决方案:

    sed 's/.*/\L&/' $inputFile | sort -o $inputFile
    

    解释s/.*/\L&amp;/ 表示使用\L 将整行 (.*) 转换为小写。 &amp; 代表匹配的模式。

    【讨论】:

    • 或者,如果你想通过 STDIN 管道,echo HELLO | sed -e 's/.*/\L&amp;/' ==> hello
    【解决方案3】:

    您可以使用 sort 的-o 标志来执行排序和重定向回原始文件:

    awk '{ print tolower($0) }' $inputFile | sort -o $inputFile
    

    【讨论】:

    • 我可能是错的,但这对我来说看起来不安全,我不会在$inputfile 上花钱,在sort 完成之前不会被覆盖。是的,sort -o 允许您指定与输入文件相同的名称并保证它的安全性,但这不是您正在使用该脚本执行的操作,因此sort 可能认为在它完成读取所有内容之前初始化输出文件是可以的输入。
    • @EdMorton - 好点;可能取决于排序实现。例如,这个GNU sort manual page 表示它是安全的,除非你使用--merge(-m) 标志。
    猜你喜欢
    • 1970-01-01
    • 2011-10-03
    • 2013-12-02
    • 2016-09-16
    • 2012-06-25
    • 1970-01-01
    • 2020-04-10
    • 2011-01-16
    • 1970-01-01
    相关资源
    最近更新 更多