我试图从文本文件中提取大括号之间的所有内容,并将输出写入另一个文本文件。我能够构造一个正则表达式来匹配{}之间的所有内容并且它工作正常(我编写了一个简单的java程序来测试它)但是我在unix中不是很强大因此不确定如何在unix中使用这个正则表达式。
以下正则表达式匹配{}之间的所有内容(也适用于jedit)
\{([^}]+)\}
我尝试了下面的sed命令,
cat samplefile | sed -e 's/.*\{\([^}]+\)\}.*/\1/g'
我收到以下错误。
sed: -e expression #1, char 24: Invalid preceding regular expression
在我发现正则表达式匹配[]之间的所有内容之间它很有效。不知道我哪里错了。有人可以帮我修复我的正则表达式吗?
cat file |sed -e 's/.*\[\([^]]*\)\].*/\1/g'
修改1:
解决方案:
cat file | sed -e 's/.*{\([^}]\+\)}.*/\1/g' --> works
答案 0 :(得分:3)
你必须逃避+量词
答案 1 :(得分:1)
我知道你已经解决了这个问题,但大多数unix机器都有一个perl解释器,而且该语言有一个内置模块,可以解决文本问题,这种分隔符很难实现,它是Text::Balanced
。这是一个测试:
假设这个随机文本(取自问题:-),在花括号之间添加了一些文本并保存为infile
文件:
I am trying to extract {everything between braces} from a text file and
write the output to another text file. I was able to {construct a regular
expression} to match everything between {} and it works fine (I wrote a
simple {java program} to test it) but I not {very strong} in unix hence not
sure how to use this regular expression in unix.
计划script.pl
:
#!/usr/bin/env perl
use warnings;
use strict;
use Text::Balanced qw<extract_bracketed>;
my $str = do { undef $/; <> };
while ( my @result = extract_bracketed( $str, '{}', '[^{]*' ) ) {
last unless defined $result[0];
$result[0] =~ s/\n//g;
$result[0] = substr $result[0], 1, length( $result[0] ) - 2;
printf qq|%s\n|, $result[0];
}
读取变量中的整个文件并解析它寻找一对花括号,因为每个循环都保存在数组的第一个位置@result
里面的文本,所以我删除任何换行符,导致并且尾随花括号并打印出来。
像以下一样运行:
perl script.pl infile
产量:
everything between braces
construct a regular expression
java program
very strong
请注意,它正确解析了第三行中的空白对。另外还有一个换行符(第二行),当有几行在同一行时,就像在第四行中一样。