2

我正在尝试编写一个脚本,该脚本将接受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> inputFile,但这也不起作用。

样品inputFile

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

所需的输出(回到原来的inputFile):

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

3 回答 3

3

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

awk '{ print tolower($0) }' $inputFile | sort -o $inputFile
于 2015-02-06T19:39:24.657 回答
1

sed类似的解决方案:

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

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

于 2015-02-07T09:40:39.160 回答
0

您可以使用 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
于 2015-02-07T21:02:57.623 回答