gpt4 book ai didi

perl - 用 bash sed 或脚本语言(TCL、perl)替换文件中的字符串

转载 作者:行者123 更新时间:2023-11-29 09:40:23 25 4
gpt4 key购买 nike

我有一个 C++ 源文件列表,其结构如下:

// A lot of stuff
#include <current/parser/support/base.hpp>
// ...
#include <current/parser/iterators/begin.hpp>
// ...

我需要替换像

这样的行
#include <current/parser/support/base.hpp>

#include <support_base.hpp>

即省略current/parser,将分隔符(/)替换为_。这可能与 bash sed 或脚本语言有关吗?

编辑:抱歉,忘了说我想替换类似

的东西
#include <current/parser/*/*/*/*>

任何东西都可以在 current/parser 之后,并且具有任何深度。

最佳答案

使用 Tcl:

# Open the file for reading
set fin [open filein.c r]
# Open the file to write the output
set fout [open fileout.c w]

# Loop through each line
while {[gets $fin line] != -1} {
# Check for lines beginning with "^#include <current/parser/"
#
# ^ matches the beginning of the line
# ([^>]*) matches the part after "#include <current/parser/" and stores it
# in the variable 'match'

if {[regexp {^#include <current/parser/([^>]*)>} $line - match]} {
# the edited line is now built using the match from above after replacing
# forward slashes with underscores
set newline "#include <[string map {/ _} $match]>"
} else {
set newline $line
}
# Put output to the file
puts $fout $newline
}

# Close all channels
close $fin
close $fout

使用提供的输入输出:

// A lot of stuff
#include <support_base.hpp>
// ...
#include <iterators_begin.hpp>
// ...

Demo on codepad (我稍微编辑了代码,因为我无法打开一个 channel 来读取/写入那里的文件)

关于perl - 用 bash sed 或脚本语言(TCL、perl)替换文件中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24136557/

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