对 sed 输出进行排序会在 Solaris 10 和 11 上给出不同的结果

sorting the sed output gives different results on Solaris 10 and 11

我有一个从文件名中提取日期并计算唯一天数的命令:

find xml/ -type f -name "*.201604*.xml" | head -5 | sed "s/.*\.\(2016[0-9]\{4\}\)\(.*\)//g" | sort | uniq -c

Solaris 10 上的结果是:

# find xml/ -type f -name "*.201604*.xml" | head -5 | sed "s/.*\.\(2016[0-9]\{4\}\)\(.*\)//g" | sort | uniq -c
   2 20160412
   1 20160417
   2 20160418
# uname -a
SunOS localhost 5.10 Generic_150400-26 sun4u sparc SUNW,SPARC-Enterprise
# which sed sort
/usr/bin/sed
/usr/bin/sort

Solaris 11 上的结果是:

$ find xml/ -type f -name "*.201604*.xml" | head -5 | sed "s/.*\.\(2016[0-9]\{4\}\)\(.*\)//g" | sort | uniq -c
   1 20160401
   1 20160403
   1 20160405
   1 xml/results/subres/ABC.DEF.GH01.20160401224003.123456.123456.xml
   1 xml/results/subres/ABC.DEF.GH02.20160412124035.234567.234567.xml
$ uname -a
SunOS localhost 5.11 11.2 sun4v sparc sun4v
$ which sed sort
/usr/bin/sed
/usr/bin/sort

出于某种原因,在 Solaris 11 上,sort 命令导致 sed 到 return 完整文件路径,而不是匹配的正则表达式。

尽管它可以正常工作 (Solaris 11):

$ find xml/ -type f -name "*.201604*.xml" | head -5 | sed "s/.*\.\(2016[0-9]\{4\}\)\(.*\)//g"
20160403
20160401
20160401
20160412
20160405

为什么?还有其他人有这种行为吗?

find 给出未排序的结果。在使用 head -5.
之前对 find 的输出进行排序 还有set LC_ALL=C

您在调用 sed 之后调用 sort,因此 sort 不会影响 sed 的行为方式。您只是在每台机器上选择不同版本的 sed,可能一个来自 /bin,它不理解转义的 ERE 字符来创建 RE 间隔(\{4\}),另一个来自 /usr/xpg4/bin 或类似的。

你说 Solaris 11 行为不同的情况 with/without 如果没有一些环境变化,排序就不可能发生 - 也许你在不同的 shell 或 运行 不同的安装脚本或东西。

在两台机器上执行 where sed(或 which sedwhence sed 或...)

通过 unset LANG 解决了问题。它被设置为 en_US.UTF-8man 表示 LANG 影响 sed 命令执行。