您要求sed 解决方案,但awk 解决方案更简单,在这种情况下性能更好,因为您可以通过= 轻松地将行拆分为2 个字段然后选择性地将gsub() 应用于仅第一个字段以替换感兴趣的字符:
$ awk -F= '{ gsub("[./-]", "_", $1); print $1 FS $2 }' <<< 'Int/domain-home.dir=/etc/int'
Int_domain_home_dir=/etc/int
-F= 告诉awk 将输入拆分为= 的字段,这与手头的输入导致$1(第一个字段)包含行的前半部分,在@ 之前987654330@,和$2(第二场)第二半场,在=之后;使用-F 选项设置变量FS,即输入字段分隔符。
gsub("[./-]", "_", $1) 用$1 中的_ 全局替换集合[./-] 中的所有字符 - 即,替换第一个字段中所有出现的.、/ 或-每个都有一个_。
print $1 FS $2 打印结果:修改后的第一个字段 ($1),然后是 FS(即 =),然后是(未修改的)第二个字段 ($2)。
请注意,我使用的是 ASCII 字符。 -(HYPHEN-MINUS,代码点 0x2d)在 awk 脚本中,即使您的示例输入包含 Unicode 字符。 —(EM DASH,U+2014,UTF-8 编码 0xe2 0x80 0x94)。
如果您真的想匹配 那个,只需在上面的命令中替换它,但请注意 macOS 上的 awk 版本无法正确处理。
另一种选择是将iconv 与ASCII 音译一起使用,它将破折号翻译成常规的ASCII -:
iconv -f utf-8 -t ascii//translit <<< 'Int/domain—home.dir=/etc/int' |
awk -F= '{ gsub("[./-]", "_", $1); print $1 FS $2 }'
perl 也可以提供优雅的解决方案:
$ perl -F= -ane '$F[0] =~ tr|-/.|_|; print join("=", @F)' <<<'Int/domain-home.dir=/etc/int'
Int_domain_home_dir=/etc/int
-F=,就像 Awk 一样,告诉 Perl 在将行拆分为字段时使用 = 作为分隔符
-ane 激活字段拆分 (a),关闭隐式输出 (n),e 告诉 Perl next 参数是一个表达式(命令string) 来执行。
每行分割成的字段存储在数组@F中,其中$F[0]指的是第一个字段。
$F[0] =~ tr|-/.|-| 将所有出现的-、/ 和. 转换(替换)为_。
print join("=", @F) 从字段中重建输入行 - 现在已修改第一个字段 - 并打印结果。
根据使用的 awk 实现,这实际上可能更快(见下文)。
sed 不是这项工作的最佳工具,这也反映在解决方案的相对性能中:
来自我的 macOS 10.12 机器的示例时序(GNU sed 4.2.2、Mawk awk 1.3.4、perl v5.18.2,使用输入文件 file,其中包含 100 万份示例输入line) - 对它们持保留态度,但数字的 比率 很有趣;最快的解决方案优先:
# This answer's awk answer.
# Note: Mawk is much faster here than GNU Awk and BSD Awk.
$ time awk -F= '{ gsub("[./-]", "_", $1); print $1 FS $2 }' file >/dev/null
real 0m0.657s
# This answer's perl solution:
# Note: On macOS, this outperforms the Awk solution when using either
# GNU Awk or BSD Awk.
$ time perl -F= -ane '$F[0] =~ tr|-/.|_|; print join("=", @F)' file >/dev/null
real 0m1.656s
# Sundeep's perl solution with tr///
$ time perl -pe 's#^[^=]+#$&=~tr|/.-|_|r#e' file >/dev/null
real 0m2.370s
# Sundeep's perl solution with s///
$ time perl -pe 's#^[^=]+#$&=~s|[/.-]|_|gr#e' file >/dev/null
real 0m3.540s
# Cyrus' solution.
$ time sed 'h;s/[^=]*//;x;s/=.*//;s/[/.-]/_/g;G;s/\n//' file >/dev/null
real 0m4.090s
# Kenavoz' solution.
# Note: The 3-byte UTF-8 em dash is NOT included in the char. set,
# for consistency of comparison with the other solutions.
# Interestingly, adding the em dash adds another 2 seconds or so.
$ time sed ':a;s/[-/.]\(.*=\)/_\1/;ta' file >/dev/null
real 0m9.036s
如您所见,awk 解决方案是迄今为止最快的,而 line-internal-loop sed 解决方案的性能预计最差,大约是 12 倍。