【问题标题】:a basic require system with bash and sed: substitute for the contents of a file带有 bash 和 sed 的基本要求系统:替换文件的内容
【发布时间】:2013-12-04 12:17:42
【问题描述】:

我想使用 sed 查找类似 @​​987654321@ 的内容,并将该行替换为 file.sh 的内容。

我得到的最接近的是

echo "#<file.sh>" | sed "s/\#<\(.*\)>/\1/"

然后将#&lt;file.sh&gt; 替换为file.sh。我现在想用文件的内容替换它,而不是我找到的文件名。

我试过了

echo "#<file.sh>" | sed "s/\#<\(.*\)>/$(cat \1)/"

但最后会说cat: 1: inexisting file or directory,所以它试图读取\1而不是我保存在\1中的file.sh。

【问题讨论】:

    标签: regex bash shell sed include


    【解决方案1】:

    假设您有GNU sed,以下可能对您有用:

    sed '/#<\(.*\)>/s|.*|cat \1|e' filename
    

    例子:

    $ cat foo 
    abc
    #</tmp/o/a.c>
    def
    $ cat /tmp/o/a.c
    #include <stdio.h>
    
    int main() {
    }
    $ sed 's|#<\(.*\)>|cat \1|e' foo
    abc
    #include <stdio.h>
    
    int main() {
    }
    def
    

    【讨论】:

    • @JoãoPintoJerónimo 是的。如果您使用的是GNU sed,它应该
    • 我想我应该是,我在一个 ubuntu 盒子里......我得到了这个:sed: -e expression #1, character 24: reference \1 invalid in RHS of command 's'
    • @JoãoPintoJerónimo 你确定你没有错字吗?
    • @JoãoPintoJerónimo 我添加了一个示例来演示它的工作原理!
    【解决方案2】:

    根据@devnull 的回答,尝试以下操作:

    sed '/\#<.*>/s|#<\(.*\)>|cat \1|e' filename
    

    在我的系统上,反向引用必须在搜索和替换的搜索部分。您还需要避免一开始收集的#。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-09
      • 2021-03-21
      • 1970-01-01
      • 2012-09-10
      • 1970-01-01
      • 1970-01-01
      • 2020-10-31
      • 1970-01-01
      相关资源
      最近更新 更多