Sed语法差异MacOS与GNU [英] Sed syntax difference MacOS vs GNU

查看:36
本文介绍了Sed语法差异MacOS与GNU的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下一段代码可以在MacOS上完美运行,但不能在GNU上运行(我正在使用MinGW):

I have the following piece of code that works perfectly on MacOS, but doesn't work on GNU (I'm using MinGW):

filename=$1
iter_count=$((${#src_op_lst[@]} -1))
for i in $(eval echo "{0..$iter_count}");do
    echo "Checking File :" $filename
    sed -i "" "s/[[:<:]]"${src_op_lst[$i]}"[[:>:]]/"${tgt_op_lst[$i]}"/g" $filename
done

我想原因是 sed 的语法不同,但是我不知道如何使它在GNU上工作.我尝试使用 sed -i -e ... ,但是sed给我以下错误: -e表达式#1,字符50:无效的字符类名称.

I guess the reason is that sed syntax is differ, but I have no idea how to make it work on GNU. I've tried to use sed -i -e ..., but sed gives me following error: -e expression #1, char 50: Invalid character class name.

我对bash脚本非常陌生,如果这个问题很愚蠢,请原谅.任何帮助将不胜感激!

I'm very new to bash scripting, excuse me if this question is stupid. Any help would be greatly appreciated!

推荐答案

[[::<:]] [[:>:]] 是标记MacOS的 sed 解释为方向性单词边界:第一个可让您检查单词开头是否匹配,第二个则可检查单词结尾是否匹配.
这些可以确保您要替换整个单词而不是单词的一部分(例如,在尝试替换 pro <时,避免将 professor 更改为 confessor /code>和 con ).

[[:<:]] and [[:>:]] are tokens that MacOS's sed inteprets as directional word-boundaries : the first one lets you check you're matching at the start of a word and the second at the end of a word.
Those let you make sure you're replacing whole words rather than parts of words (e.g. avoiding to change professor into confessor when you're trying to replace pro with con).

GNU sed中的精确等效项是 \< \> .

The exact equivalent in GNU sed would be \< and \>.

但是,作为熟悉regex但不一定要使用不计其数的不同实现的人,我建议您使用更常见的 \ b 而不是同时使用 \< \> .
这是一个无方向的单词边界,如果您位于单词的开头或结尾,则该单词边界将匹配.在您的情况下(大多数情况下),它将产生完全相同的结果,并且将来的维护者将更可能熟悉它,而不会经历您刚刚经历的艰辛.

However, as someone familiar with regex but not necessarily with the bazillion different implementations, I would suggest you use the more common \b instead of both \< and \>.
It's a direction-less word boundary which will match if you're either at the start or the end of a word. It will produce the exact same result in your case (and in most cases) and future maintainers will be more likely to be familiar with it and not go through the struggle you just experienced.

这篇关于Sed语法差异MacOS与GNU的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆