如何使用sed,awk或gawk只打印匹配的内容?

时间:2009-11-14 08:34:14

标签: regex unix sed awk gawk

我看到很多关于如何使用sed,awk或gawk进行搜索和替换等操作的示例和手册页。

但在我的情况下,我有一个正则表达式,我想对文本文件运行以提取特定值。我不想做搜索和替换。这是从bash调用的。我们来举个例子:

正则表达式示例:

.*abc([0-9]+)xyz.*

示例输入文件:

a
b
c
abc12345xyz
a
b
c

这听起来很简单,我无法弄清楚如何正确调用sed / awk / gawk。我希望做的是从我的bash脚本中得到:

myvalue=$( sed <...something...> input.txt )

我尝试过的事情包括:

sed -e 's/.*([0-9]).*/\\1/g' example.txt # extracts the entire input file
sed -n 's/.*([0-9]).*/\\1/g' example.txt # extracts nothing

13 个答案:

答案 0 :(得分:42)

我的sed(Mac OS X)无法与+一起使用。我尝试了*,并为打印匹配添加了p标记:

sed -n 's/^.*abc\([0-9]*\)xyz.*$/\1/p' example.txt

为了匹配至少一个没有+的数字字符,我会使用:

sed -n 's/^.*abc\([0-9][0-9]*\)xyz.*$/\1/p' example.txt

答案 1 :(得分:32)

您可以使用sed执行此操作

 sed -rn 's/.*abc([0-9]+)xyz.*/\1/gp'
  • -n不打印生成的行
  • -r这样就可以让你没有捕获组parens ()的转义。
  • \1捕获组匹配
  • /g全球比赛
  • /p打印结果

我为自己写了一个tool,这使得这个更容易

rip 'abc(\d+)xyz' '$1'

答案 2 :(得分:17)

我使用perl让自己更容易。 e.g。

perl -ne 'print $1 if /.*abc([0-9]+)xyz.*/'

这运行Perl,-n选项指示Perl一次从STDIN读取一行并执行代码。 -e选项指定要运行的指令。

该指令在读取行上运行正则表达式,如果匹配则打印出第一组bracks($1)的内容。

你可以这样做,最后还会有多个文件名。 e.g。

perl -ne 'print $1 if /.*abc([0-9]+)xyz.*/' example1.txt example2.txt

答案 3 :(得分:5)

如果您的grep版本支持,则可以使用-o选项打印 与您的正则表达式匹配的任何行的部分。

如果没有,那么这是我能提出的最好的sed

sed -e '/[0-9]/!d' -e 's/^[^0-9]*//' -e 's/[^0-9]*$//'

...删除/跳过没有数字,对于其余行,删除所有前导和尾随非数字字符。 (我只是猜测你的意图是从包含一行的每一行中提取数字。)

类似的问题:

sed -e 's/.*\([0-9]*\).*/&/' 

....或

sed -e 's/.*\([0-9]*\).*/\1/'

... sed仅支持“贪婪”匹配...所以第一个。*将匹配该行的其余部分。除非我们可以使用否定的字符类来实现非贪婪的匹配...或者sed的版本与其正则表达式的Perl兼容或其他扩展,我们无法从中提取精确的模式匹配模式空间(一条线)。

答案 4 :(得分:3)

您可以awkmatch()一起使用来访问捕获的群组:

$ awk 'match($0, /abc([0-9]+)xyz/, matches) {print matches[1]}' file
12345

这会尝试匹配模式abc[0-9]+xyz。如果它这样做,它会将其切片存储在数组matches中,其第一项是块[0-9]+。由于match() 返回子字符串开始处的字符位置或索引(1,如果它从字符串的开头开始),它会触发print操作。< / p>

使用grep,您可以使用后视和前瞻:

$ grep -oP '(?<=abc)[0-9]+(?=xyz)' file
12345

$ grep -oP 'abc\K[0-9]+(?=xyz)' file
12345

这会在[0-9]+abc内检查模式xyz并打印数字。

答案 5 :(得分:2)

perl是最干净的语法,但是如果你没有perl(并不总是那里,我理解),那么使用gawk和正则表达式组件的唯一方法就是使用gensub功能。

gawk '/abc[0-9]+xyz/ { print gensub(/.*([0-9]+).*/,"\\1","g"); }' < file

示例输入文件的输出将是

12345

注意:gensub替换整个正则表达式(在//之间),所以你需要在([0-9] +)之前和之后放置。*来删除替换前后的数字之前和之后的文本

答案 6 :(得分:1)

如果要选择行,请删除不需要的位:

egrep 'abc[0-9]+xyz' inputFile | sed -e 's/^.*abc//' -e 's/xyz.*$//'

它基本上用egrep选择你想要的行,然后使用sed去掉数字前后的位。

你可以在这里看到这个:

pax> echo 'a
b
c
abc12345xyz
a
b
c' | egrep 'abc[0-9]+xyz' | sed -e 's/^.*abc//' -e 's/xyz.*$//'
12345
pax> 

更新:显然如果你的实际情况比较复杂,RE需要我修改。例如,如果在开始和结束时总是将一个数字埋在零或更多非数字中:

egrep '[^0-9]*[0-9]+[^0-9]*$' inputFile | sed -e 's/^[^0-9]*//' -e 's/[^0-9]*$//'

答案 7 :(得分:0)

OP的情况没有指定一行上可以有多个匹配项,但是对于Google流量,我也将为此添加一个示例。

由于OP的需要是从模式中提取组,因此使用grep -o将需要2遍。但是,我仍然发现这是完成工作的最直观的方式。

$ cat > example.txt <<TXT
a
b
c
abc12345xyz
a
abc23451xyz asdf abc34512xyz
c
TXT

$ cat example.txt | grep -oE 'abc([0-9]+)xyz'
abc12345xyz
abc23451xyz
abc34512xyz

$ cat example.txt | grep -oE 'abc([0-9]+)xyz' | grep -oE '[0-9]+'
12345
23451
34512

由于处理器时间基本上是免费的,但是人类可读性却是无价的,所以我倾向于基于“一年以后,我打算怎么做”这个问题来重构代码。实际上,对于我打算公开或与我的团队共享的代码,我什至会打开man grep来找出长选项,然后用长选项代替。像这样:grep --only-matching --extended-regexp

答案 8 :(得分:0)

为什么还需要匹配组

gawk/mawk/mawk2 'BEGIN{ FS="(^.*abc|xyz.*$)" } ($2 ~ /^[0-9]+$/) {print $2}'

让 FS 收走线的两端。

如果 $2,FS 没有吞下的剩余部分,不包含非数字字符,那就是你打印出来的答案。

如果您特别谨慎,请确认 $1 和 $3 的长度均为零。

** 在实现零长度 $2 后编辑的答案会绊倒我以前的解决方案

答案 9 :(得分:0)

awk 频道中有一段标准代码,名为“FindAllMatches”,但它仍然非常手动,字面意思是,只是 while()match()substr() 的长循环,更多substr(),然后冲洗并重复。

如果您正在寻找有关如何仅获取匹配部分的想法,但是对于每行匹配多次或根本不匹配的复杂正则表达式,请尝试以下操作:

mawk/mawk2/gawk 'BEGIN { srand(); for(x = 0; x < 128; x++ ) { 

    alnumstr = sprintf("%s%c", alnumstr , x) 
 }; 
 gsub(/[^[:alnum:]_=]+|[AEIOUaeiou]+/, "", alnumstr) 
                       
                    # resulting str should be 44-chars long :
                    # all digits, non-vowels, equal sign =, and underscore _

 x = 10; do { nonceFS = nonceFS substr(alnumstr, 1 + int(44*rand()), 1)

 } while ( --x );   # you can pick any level of precision you need.
                    # 10 chars randomly among the set is approx. 54-bits 
                    #
                    # i prefer this set over all ASCII being these 
                    # just about never require escaping 
                    # feel free to skip the _ or = or r/t/b/v/f/0 if you're concerned.
                    #
                    # now you've made a random nonce that can be 
                    # inserted right in the middle of just about ANYTHING
                    # -- ASCII, Unicode, binary data -- (1) which will always fully
                    # print out, (2) has extremely low chance of actually
                    # appearing inside any real word data, and (3) even lower chance
                    # it accidentally alters the meaning of the underlying data.
                    # (so intentionally leaving them in there and 
                    # passing it along unix pipes remains quite harmless)
                    #
                    # this is essentially the lazy man's approach to making nonces
                    # that kinda-sorta have some resemblance to base64
                    # encoded, without having to write such a module (unless u have
                    # one for awk handy)


    regex1 = (..);  # build whatever regex you want here

    FS = OFS = nonceFS;

 } $0 ~ regex1 { 

    gsub(regex1, nonceFS "&" nonceFS); $0 = $0;  

                   # now you've essentially replicated what gawk patsplit( ) does,
                   # or gawk's split(..., seps) tracking 2 arrays one for the data
                   # in between, and one for the seps.
                   #
                   # via this method, that can all be done upon the entire $0,
                   # without any of the hassle (and slow downs) of 
                   # reading from associatively-hashed arrays,
                   # 
                   # simply print out all your even numbered columns
                   # those will be the parts of "just the match"

如果您还运行另一个 OFS = ""; $1 = $1; ,现在而不是需要 4 个参数 split()patsplit(),这两个参数都是专用于查看正则表达式 sep 是什么,现在整个$0 的字段采用 data1-sep1-data2-sep2-.... 模式,..... 而 $0 看起来与您第一次阅读该行时完全相同。直接向上 print 将与读取时立即打印相同。

一旦我使用代表有效 UTF8 字符的正则表达式对其进行了极端测试。 mawk2 可能需要 30 秒左右的时间来处理一个包含大量 CJK unicode 的 167MB 文本文件,所有这些文件都一次性读入 0 美元,然后启动这个拆分逻辑,导致 NF 约为 175,000,000,每个字段都是 1-single ASCII 或多字节 UTF8 Unicode 字符。

答案 10 :(得分:-1)

你可以用shell

来做
while read -r line
do
    case "$line" in
        *abc*[0-9]*xyz* ) 
            t="${line##abc}"
            echo "num is ${t%%xyz}";;
    esac
done <"file"

答案 11 :(得分:-3)

对于awk。我会使用以下脚本:

/.*abc([0-9]+)xyz.*/ {
            print $0;
            next;
            }
            {
            /* default, do nothing */
            }

答案 12 :(得分:-3)

gawk '/.*abc([0-9]+)xyz.*/' file
相关问题