gpt4 book ai didi

正则表达式替换多个文件

转载 作者:太空狗 更新时间:2023-10-29 11:05:02 27 4
gpt4 key购买 nike

我需要将一个正则表达式的所有实例替换为根目录下多个目录中的多个文件中的另一个正则表达式。

例子:文件结构:

.
|---src
| |---Module
| | |---someclass.cpp
| |---main.cpp
|
|---include
|---Module
|---someclass.hpp

基本上是这样,但有更多的文件和文件夹。

我需要搜索正则表达式 \(std::vector<.*>并将其所有实例替换为 \(std::vector<.*> const&棘手的部分似乎是确保 < 之间的内容和 >保持不变。

例如它将匹配 (std::vector<int>并将其替换为 (std::vector<int> const& .一个更复杂的例子是:
匹配:(std::vector<std::map<std::string, int>>
替换为:(std::vector<std::map<std::string, int>> const&

最佳答案

如果示例中最后的“>”是每一行的最后一个“>”,那么这应该有效:

find root -name '*.cpp' -print0 |
xargs -0 sed -i 's/\((std::vector<.*>\)\([^>]*$\)/\1 const\&\2/'

在单个文件上尝试 sed,并且先不使用 -i,例如:

$ cat file
(std::vector<int>
(std::vector<int> foo
(std::vector<std::map<std::string, int>>
(std::vector<std::map<std::string, int>> bar

$ sed 's/\((std::vector<.*>\)\([^>]*$\)/\1 const\&\2/' file
(std::vector<int> const&
(std::vector<int> const& foo
(std::vector<std::map<std::string, int>> const&
(std::vector<std::map<std::string, int>> const& bar

如果在您的示例中的最后一个之后可以有“>”,那么解决方案很重要,请发布一些有代表性的样本输入和预期输出。

哦,搞什么鬼,这是不平凡的脚本:

$ cat file
(std::vector<int>
(std::vector<int> foo
(std::vector<int> with extra > in text
(std::vector<std::map<std::string, int>>
(std::vector<std::map<std::string, int>> bar
(std::vector<std::map<std::string, int>> and here is > again

$ awk -v FS= -v str="(std::vector<" '
BEGIN{ lgth=length(str) }
start=index($0,str) {
cnt = 1
for(i=(start+lgth);(i<=NF) && (cnt!=0);i++) {
if ($i == "<") cnt++
if ($i == ">") cnt--
}
$0 = substr($0,1,i-1) " const&" substr($0,i)
}1' file
(std::vector<int> const&
(std::vector<int> const& foo
(std::vector<int> const& with extra > in text
(std::vector<std::map<std::string, int>> const&
(std::vector<std::map<std::string, int>> const& bar
(std::vector<std::map<std::string, int>> const& and here is > again

在 while 循环中执行:

find root -name '*.cpp' -print |
while IFS= read -r file; do
awk -v FS= -v str="(std::vector<" '
BEGIN{ lgth=length(str) }
start=index($0,str) {
cnt = 1
for(i=(start+lgth);(i<=NF) && (cnt!=0);i++) {
if ($i == "<") cnt++
if ($i == ">") cnt--
}
$0 = substr($0,1,i-1) " const&" substr($0,i)
}1' "$file" > tmp &&
mv tmp "$file"
done

如果您的文件名包含换行符,那将不起作用,但如果您有换行符,您应该只修复它们。

关于正则表达式替换多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15198494/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com