我正在尝试使用 Perl 重新排序 md5 文件的内容。对于每一行,我想要不带路径的文件名,然后是哈希值。我想出的最好的命令是:
$ perl -pe 's|^([[:alnum:]]+).*?([^/]+)$|$2 $1|' DCIM.md5
输入文件 (DCIM.md5
) 由 Linux 上的 md5sum
生成。它看起来像这样:
e26ff03dc1bac80226e200c0c63d17a2 ./Path1/IMG_20150201_160548.jpg
01f92572e4c6f2ea42bd904497e4f939 ./Path 2/IMG_20150204_190528.jpg
afce027c977944188b4f97c5dd1bd101 ./Path3/Path 4/IMG_20151011_193008.jpg
- 哈希值与
中的第一组([[:alnum:]]+)
匹配 正则表达式。 - 然后空格和文件路径是
与.*?
. 匹配
- 然后文件名通过
([^/]+)
进行匹配。 - 表达式用
^
括起来(这里显然不是必需的) 和$
。如果没有$
,表达式不会输出我期望的内容。 - 我使用
|
而不是/
作为分隔符,以避免在文件路径中转义它。
该命令返回:
IMG_20150201_160548.jpg
e26ff03dc1bac80226e200c0c63d17a2IMG_20150204_190528.jpg
01f92572e4c6f2ea42bd904497e4f939IMG_20151011_193008.jpg
afce027c977944188b4f97c5dd1bd101IMG_20151011_195133.jpg
匹配正确,输出序列正确(文件名没有路径,然后是散列),但间距不正确:文件名后面有一个换行符。我期望它在哈希之后,如下所示:
IMG_20150201_160548.jpg e26ff03dc1bac80226e200c0c63d17a2
IMG_20150204_190528.jpg 01f92572e4c6f2ea42bd904497e4f939
IMG_20151011_193008.jpg afce027c977944188b4f97c5dd1bd101
在我看来,我的命令输出换行符,但我不知道如何改变这种行为。 或者问题可能来自 shell,而不是命令?
最后,一些版本信息:
$ perl -version
This is perl 5, version 22, subversion 1 (v5.22.1) built for i686-linux-gnu-thread-multi-64int
(with 69 registered patches, see perl -V for more detail)
最佳答案
[^/]+
匹配换行符,因此输入中的内容是 $2
的一部分,它会首先放入转换后的 $_
($1
中没有换行符,因此 $_
末尾也没有换行符...)
解决方案:阅读 perlrun 中的 -l
选项。特别是:
-l[octnum] enables automatic line-ending processing. It has two separate effects. First, it automatically chomps $/ (the input record separator) when used with -n or -p. Second, it assigns $\ (the output record separator) to have the value of octnum so that any print statements will have that separator added back on. If octnum is omitted, sets $\ to the current value of $/ .
关于regex - s///返回错误的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52347330/