gpt4 book ai didi

ubuntu - 在匹配行的最后一次出现后追加文本

转载 作者:行者123 更新时间:2023-12-04 18:57:41 28 4
gpt4 key购买 nike

我有一个生成一些源代码的工具。不幸的是,该工具从源代码中跳过了 using 子句。

使用像 sed 这样的实用程序,我如何在源文件中插入一行如

using namespace xyz;

只出现一次并且在最后一行之后包含 #include ?

例如
#include <string.h>
#include <stdio.h>


// some functions
void blabla();

会成为:
#include <string.h>
#include <stdio.h>

using namespace xyz;

// some functions
void blabla();

最佳答案

sed 用于在单个行上进行简单替换,仅此而已。对于其他任何你应该使用 awk 的东西:

$ awk 'NR==FNR{if (/#include/) nr=NR; next} {print; if(nr==FNR) print "\nusing namespace xyz;"}' file file
#include <string.h>
#include <stdio.h>

using namespace xyz;


// some functions
void blabla();

以上是使用 2 次传递 - 第一次找到最后一次出现 #include 的行号出现在文件中并将其行号存储在名为 nr 的变量中然后第二次在第二次通过时打印“使用...”。您可以通过更改 awk 'script' file file 来执行此操作而无需指定两次文件名。至 awk 'BEGIN{ARGV[ARGC]=ARGV[1]; ARGC++} script' file如果您更喜欢在参数列表数组中复制文件名。

或者,如果文件不是很大,您可以将其全部读入内存,然后进行替换,将整个文件视为单个字符串,例如使用 GNU awk 进行多字符 RS 和 gensub():
$ awk -vRS='^$' -voORS= '{print gensub(/(.*#include[^\n]+\n)/,"\\1\nusing namespace xyz;\n",1)}' file
#include <string.h>
#include <stdio.h>

using namespace xyz;


// some functions
void blabla();

使用其他 awk,您可以将字符串逐行构建到一个变量中,然后在 END 部分使用 match() 和 substr() 处理它:
$ awk -v ORS= '{rec = rec $0 RS} END{ if (match(rec,/.*#include[^\n]+\n/)) rec = substr(rec,1,RSTART+RLENGTH-1) "\nusing namespace xyz;\n" substr(rec,RSTART+RLENGTH); print rec}' file
#include <string.h>
#include <stdio.h>

using namespace xyz;


// some functions
void blabla();

关于ubuntu - 在匹配行的最后一次出现后追加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37781061/

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