【问题标题】:How to express variable in sed? [duplicate]如何在sed中表达变量? [复制]
【发布时间】:2021-03-15 01:53:05
【问题描述】:
$ VAR="this is working well"
$ sed -i "s/$/,$VAR/" my.txt

$ VAR="this/got/error"
$ sed -i "s/$/,$VAR/" my.txt
sed: -e expression #1, char 12: unknown option to `s

我必须将各种类型的字符串放入 $VAR。

有时 $VAR 不能与 sed 一起使用。 Bcoz 的特殊字符。

如何使用 sed 或正则表达式解决这个问题?

提前谢谢你。

【问题讨论】:

    标签: regex linux bash sed


    【解决方案1】:

    虽然sed 教程通常使用/ 作为搜索/替换分隔符,但您可以使用许多其他符号作为分隔符。例如s/one/two/ 也可以写成s|one|twos#one#two

    所以 - 要解决您的特定问题,解决方案很简单 - 使用不同的分隔符。

    $ cat file.txt
    1
    2
    3
    4
    
    $ VAR="this is working well"
    $ sed  's/$/,'"$VAR"'/' file.txt
    1,this is working well
    2,this is working well
    3,this is working well
    4,this is working well
    
    $ VAR="this/got/error"
    $ sed  's|$|,'"$VAR"'|' file
    1,this/got/error
    2,this/got/error
    3,this/got/error
    4,this/got/error
    $
    

    【讨论】:

      【解决方案2】:

      sed 没有变量的概念,您使用的变量在sed 甚至看到它之前就被shell 解释了。因此,如果您想使用某种可以处理任意文本的变量,则需要使用可以执行此操作的其他工具。

      例如,您可以使用 Perl 来做到这一点:

      $ perl -i 's/$/,$ENV{VAR}/g' my.txt
      

      或者你可以使用awk 和一个临时文件:

      $ awk '{ sub(/$/, "," ENVIRON["VAR"]); print }' my.txt > temp && mv temp my.txt
      

      注意使用sed -i,不管有没有这个问题,都是不可移植的。在 macOS 上,您必须使用 sed -i '',但该语法在 Linux 上不起作用。 perl -i 调用可移植到所有使用 Perl 的系统,就像使用 ruby -i 的等效技术一样。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-12
        • 2014-05-07
        • 2017-02-01
        • 1970-01-01
        • 2012-12-30
        • 1970-01-01
        • 2019-06-17
        • 1970-01-01
        相关资源
        最近更新 更多