【问题标题】:How to replace angle brackets with quotation marks如何用引号替换尖括号
【发布时间】:2015-07-30 12:03:51
【问题描述】:

我有很多源代码需要修改,就从

#include <headerA.h>

#include "headerA.h"

我尝试了一些 sed、awk 命令,但不完全确定如何进行。我在 Ubuntu 平台上工作。任何意见将不胜感激!

【问题讨论】:

    标签: linux string replace awk sed


    【解决方案1】:

    这可能对你有用:

    sed '/#include/y/<>/""/' file
    

    关注包含标题的行并翻译 (y/.../.../) 所需的字符。

    【讨论】:

      【解决方案2】:
      sed -i -E "s/^(#include )[\<]([^\>]+)[\>]/\1\\\"\2\\\"/g" sourcefile.c
      

      或者,因为我们不需要在规则中使用单引号替换变量:

      sed -i -E 's/^(#include )[\<]([^\>]+)[\>]$/\1"\2"/g'
      

      遍历工作目录的所有子目录,查找 *.c 和 *.h 文件,并将尖括号替换为引号:

      find . \( -name "*.c" -o -name "*.h" \) -print0 | xargs -n1 -0 sed -i -E 's/^(#include )[\<]([^\>]+)[\>]$/\1"\2"/g'
      

      【讨论】:

        【解决方案3】:

        这应该编辑每个文件:

        find . -name '*.[ch]' -exec \
            sed -i 's|^#include[[:blank:]]\{1,\}<\([^>]\{1,\}\)>[[:blank:]]*$|#include "\1"|' '{}' \;
        

        【讨论】:

        • 只是一个注释,你用.*$ 后面没有引用的最终信息。
        • 是的,我应该在那里改用[[:blank:]]*,这是完全正确的。我会编辑答案。
        【解决方案4】:
        find /Your/Source/Path \
         -name '*.[ch]' \
         -exec \
            sed -i '/^#include[[:blank:]]/ s/<\([^>]*\)>/"\1"/g' "{}" \
         \;
        

        会改变:

        • /Your/Source/Path 下扩展名为.h.c 的任何文件
        • &lt;&gt; 周围的任何文本,相同的文本被双引号包围
          • #include开始在线

        【讨论】:

          【解决方案5】:

          首先使用findsed,然后使用mv

          find . -name <ol_file_nme> -exec sed 's/[<>]/"/g' '{}' \; -print > <new_file_name>
          mv  <new_file_name> <ol_file_nme>
          

          【讨论】:

          • el pluse uno for use of find but note @barmar's wise admonition and solution about other uses of the &lt; and &gt; characters ; -) 祝大家好运。
          【解决方案6】:

          这样就可以了:

          sed -i '/^#include/s/[<>]/"/g' filename
          

          开头的/^#include/ 地址告诉sed 只对以#include 开头的行执行替换。 [&lt;&gt;] 是匹配&lt;&gt; 的正则表达式,它们被" 替换,g 修饰符告诉它替换行上的所有匹配项,而不仅仅是第一个。

          【讨论】:

            猜你喜欢
            • 2020-05-21
            • 2013-08-14
            • 1970-01-01
            • 2021-02-02
            • 2010-11-05
            • 1970-01-01
            • 1970-01-01
            • 2012-03-22
            相关资源
            最近更新 更多