如何添加一条额外的行,该行在包含上一行中的模式的文件中也有一个模式?

如何添加一条额外的行,该行在包含上一行中的模式的文件中也有一个模式?

我有一个文件——

something
\title{\hypertarget{A64L}{A64L(3)}}
something
\title{\hypertarget{MALLOC}{MALLOC(3)}}
something
\title{\hypertarget{STRCMP}{STRCMP(3)}}  

in 中的单词{}可以是任何内容,但在 Continuous 中是相同的{}
我想要得到

something
\title{\hypertarget{A64L}{A64L(3)}}
\addcontentsline{A64L}
something
\title{\hypertarget{MALLOC}{MALLOC(3)}}
\addcontentsline{MALLOC}
something
\title{\hypertarget{STRCMP}{STRCMP(3)}}
\addcontentsline{STRCMP}  

我尝试跟随,但失败了。

sed -e /\\\\title\{\\\\hypertarget\{.*\}\{.*\(3\)\}\}/a\\\\\\addcontentsline\{\&\} filename

这是一个扩展https://tex.stackexchange.com/questions/408244/how-to-make-toc-without-having-any-section-parts-name

答案1

我不确定你到底想捕捉什么,但是

$ sed 's/\\title{\\hypertarget\({[^}]*}\).*/&\n\\addcontentsline\1/' file
something
\title{\hypertarget{A64L}{A64L(3)}}
\addcontentsline{A64L}
something
\title{\hypertarget{MALLOC}{MALLOC(3)}}
\addcontentsline{MALLOC}
something
\title{\hypertarget{STRCMP}{STRCMP(3)}}  
\addcontentsline{STRCMP}

答案2

j=`grep -o "{[0-9A-Z]\{4\}}" k1.txt | sed -r "s/\s+//g" | sed '/^$/d'`;
grep -B1 "$j" k1.txt  | sed "/title/s/.*/&\n\\\addcontentsline$j/g";
for i in `grep -o "{[A-Z]\{6\}}" k1.txt`; do
  grep -B1 $i k1.txt| sed "/title/s/.*/&\n\\\addcontentsline$i/g";
done 

输出:

something
\title{\hypertarget{A64L}{A64L(3)}}
\addcontentsline{A64L}
something
\title{\hypertarget{MALLOC}{MALLOC(3)}}
\addcontentsline{MALLOC}
something
\title{\hypertarget{STRCMP}{STRCMP(3)}}
\addcontentsline{STRCMP}

相关内容