简体   繁体   English

如何获取括号中指定的内容?

[英]How to get the contents specified in the brackets?

I want to extract the content written in a file. 我想提取写在文件中的内容。 Let us take an example 让我们举个例子

{{{
      How 
      R 
      U
}}}

{{{ Hi }}}

I want to print the output like this 我想这样打印输出

 How
 R
 U

 Hi

Well, this is not regex this is using gawk multi-character RS . 好吧,这不是regex而是使用gawk多字符RS

awk -v RS='}}}|{{{' 'NF' inputfile

      How
      R
      U

 Hi

You can pipe above command with something like this sed -r 's/^ +//g' to remove extra spaces at the start of the line. 您可以使用诸如sed -r 's/^ +//g'类的命令通过pipe传递上述命令,以删除行首的多余空格。

By using regular expressions this becomes tricky, mainly because grep or awk seem not to support the lookahead . 通过使用正则表达式,这变得很棘手,主要是因为grepawk似乎不支持lookahead

To extract or match only the text within the curly braces this regex could be used: https://regex101.com/r/ASFIFa/1 要仅提取或匹配花括号中的文本,可以使用此正则表达式: https : //regex101.com/r/ASFIFa/1

[^{\}]+(?=})

Therefore you could give a try to the ag - The Silver Searcher , something like this produce your required output: 因此,您可以尝试一下ag-Silver Searcher ,如下所示会产生所需的输出:

$ ag -o '[^{\}]+(?=})' input.txt 

To remove the leading spaces: 删除前导空格:

$ ag -o '[^{\}]+(?=})' input.txt | sed 's/^ *//'

With sed 与sed

sed '/{{{/!d;:A;/\}\}\}/!{N;bA};s/{{{//;s/}}}//;s/ *//g' infile

Or 要么

sed -E '/\{{3}/!d;:A;/\}{3}/!{N;bA};s/\{{3}| *|\}{3}//g' infile

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用正则表达式在值列表中获取括号的内容 - Get contents of brackets using regex in a list of values 使用正则表达式获取带有括号的内容 - Get the contents with the brackets using regular expression Pregmatch 以获取方括号 php 之间的内容 - Pregmatch to get contents between square brackets php 如何仅使用正则表达式获取第二或第三组括号的内容? - How do I get the contents of the second or third set of brackets with only Regular Expression? 如何批量删除txt文件中的括号及其内容? - How to mass delete brackets and their contents in txt files? 如何使用正则表达式仅替换括号内的内容? - How to replace only the contents within brackets using regular expressions? 如何在Java中替换方括号(),保留内容并制表符? - How to I replace brackets (), keep the contents and tab the result in Java? 如何在尖括号之间但没有尖括号之间获取文本? - How to get the text between angular brackets but without the angular brackets? 如何在括号正则表达式内的括号外获取字符串 - how to get string outside brackets within brackets regex 如何在括号内的括号中获取带有Java正则表达式的字符串 - How to get a String with Java regular expression in brackets within brackets
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM