代码之家  ›  专栏  ›  技术社区  ›  Tom de Geus

根据相应源中的内容在编辑器中打开头文件

  •  1
  • Tom de Geus  · 技术社区  · 7 年前

    我有几个文件同名,但扩展名不同。例如

    echo "array"   > A.hpp
    echo "..."     > A.h
    echo "content" > B.hpp
    echo "..."     > B.h
    echo "content" > C.hpp
    echo "..."     > C.h
    

    我想要一份清单 *.h 基于相应内容的文件 *.hpp 文件。 特别是我正在寻找一个一行程序来打开它们在我的编辑。

    公平的假设是 *HPP 归档相应的 *h 文件存在。此外,由于它们是源文件,因此可以假定文件名不包含空格。


    当前方法

    我知道如何获得 *HPP 基于其内容的文件。一种方法(但肯定不是唯一的或最好的)是

    find . -type f -iname '*.hpp' -print | xargs grep -i 'content' | cut -d":" -f1
    

    哪个给了

    ./B.hpp
    ./C.hpp
    

    然后在我的编辑器中打开

    st `find . -type f -iname '*.hpp' -print | xargs grep -i 'content' | cut -d":" -f1`
    

    但是我怎样才能打开相应的 *h 文件夹?

    2 回复  |  直到 7 年前
        1
  •  2
  •   rkta    7 年前

    你说你想得到 *.h 基于相应内容的文件 *.hpp 文件。

    while read -r line ; do
      echo "${line%.hpp}.h"
    done < <(grep -i 'content' *.hpp| cut -d":" -f1)
    

    BashFAQ 001 建议使用 while 循环和 read 读取数据流的命令。

    按要求提供一个衬里

    st `while IFS= read -r line ; do echo "${line%.hpp}.h"; done < <(grep -i 'content' *.hpp| cut -d":" -f1)`
    

    如果要处理包含空白的文件名,则需要使用 printf 而不是回声。

    st `while IFS= read -r line ; do printf '%q' "${line%.hpp}.h"; done < <(grep -i 'content' *.hpp| cut -d":" -f1)`
    

    这个 %q 让printf格式化输出,以便它可以重用为shell输入。

    解释

    你必须从后面看。首先,我们将所有以 .hpp 在字符串的当前目录中 'content' 把所有的东西都剪掉,除了名字。 while循环将读取grep的输出并将basename赋给变量 line .

    在while循环中,我们使用bash的 parameter substitution 更改文件扩展名的步骤 .h HPP .

        2
  •  1
  •   Ed Morton    7 年前

    你的问题仍然不清楚,但这就是你想做的(使用GNUawk gensub() ?

    $ awk '/content/{print gensub(/[^.]+$/,"h",1,FILENAME)}' *.hpp
    B.h
    C.h