我有几个同名但扩展名不同的文件。例如
echo "array" > A.hpp
echo "..." > A.h
echo "content" > B.hpp
echo "..." > B.h
echo "content" > C.hpp
echo "..." > C.h
我想根据相应的*.hpp
文件中的一些内容得到一个*.h
文件的列表。特别是我我正在寻找可以在我的编辑器中打开它们的单行代码。
公平地假设每个*.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
文件呢?
最佳答案
你说你想根据对应的*.hpp
文件中的一些内容得到一个*.h
文件的列表。
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
而不是 echo。
st `while IFS= read -r line ; do printf '%q' "${line%.hpp}.h"; done < <(grep -i 'content' *.hpp| cut -d":" -f1)`
%q
允许 printf 格式化输出,以便它可以重新用作 shell 输入。
解释
你必须从后面读它。首先,我们为字符串 'content'
搜索当前目录中以 .hpp
结尾的所有文件,并剪切除基本名称之外的所有内容。
while 循环将读取 grep 的输出并将基本名称分配给变量 line
。
在 while 循环中我们使用 bash 的 parameter substitution将文件扩展名从 .h
更改为 .hpp
。
关于linux - 根据相应源中的内容在编辑器中打开头文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51342086/