如何在保留原始文本的特定模式后在括号内添加文本

时间:2016-01-08 16:06:26

标签: regex bash awk sed latex

我有一个乳胶文件,我想在其中替换\ caption环境中的内容。

特别是,我想使用粗体文字并更改大小。举个例子:

%ORIGINAL
\caption{ Some text }
%...
\env2{ \caption{ Other text } }

这样的事情

%NEW FILE
\caption{ \scriptsize\textbf{ Some text } }
%...
\env2 { \caption {\scriptsize\textbf{ Other text } } }

我能够使用sed在两个模式“\ caption {”和结束“}”之间提取文本,如下所示:How to use sed/grep to extract text between two words?

我也可以使用已知字符串替换内部文本,如下所示:replace a unknown string between two known strings with sed

我的问题是:如何将未知字符串保留在新添加的环境中,只使用单个sed命令并仅替换周围的字符串?也许是这样的:

START-PATTERN [new-environments] [Inner-text] [closing-brackets] END-PATTERN

谢谢。

2 个答案:

答案 0 :(得分:1)

这是你的例子中的sed。

sed 's/\\caption\s*{\([^}]*\)}/ \\caption {\\scriptsize\\textbf{ \1 } }/g'

根据您的需要进行更改。

说明:

\\caption\s*{\([^}]*\)}

  • \\匹配字符\字面
  • 标题字面匹配字符标题
  • \ s *匹配零和无限次之间的任何空格字符
  • {匹配字符{字面意思
  • ([^}] *)获取所有内容,直到找到},obs:capture group
  • }匹配字符}字面意思

\\caption {\\scriptsize\\textbf{ \1 } }

用上面的文字替换匹配的文本,并将匹配的第一组信息放在\ textbf()里面(例如:一些文本或其他文本)

答案 1 :(得分:1)

<强>桑达

这是一个sed oneliner,适用于处理转义大括号(\{\}正确的monoline块:

 sed -r 's/\\caption[ \t]*\{(([^\{}]|\\.)*)\}/\\caption\{\\scriptsize\\textbf\{\1\}\}/g' input.file

sed每行编辑性质不允许此操作适用于多行块。

<强>的Perl

要避免此限制,您可以使用与perl相同的正则表达式(在slurp mode块中启用BEGIN):

# Note double backslash \\ inside [...], not required in sed
perl -pe 'BEGIN{undef $/;} s/\\caption[ \t]*\{(([^\\{}]|\\.)*)\}/\\caption\{\\scriptsize\\textbf\{\1\}\}/g' input.file

Regex101 Demo

<强>输入

%ORIGINAL
\caption{ \{Some text\}
    some other \{text\}
}
%...
\env2{ \caption{ Other text } }

<强>输出

%ORIGINAL
\caption{\scriptsize\textbf{ \{Some text\}
    some other \{text\}
}}
%...
\env2{ \caption{\scriptsize\textbf{ Other text }} }