如何使用sed,awk中,或只呆呆地看着是什么匹配打印? [英] how to use sed, awk, or gawk to print only what is matched?
问题描述
我看到很多的例子和手册页有关如何做的事情一样搜索和替换使用SED,AWK,或呆呆地看着。
但在我而言,我有我想对一个文本文件来运行提取特定值的常规前pression。我不想做搜索和替换。这是从bash的调用。让我们用一个例子:
例常的前pression:
。* ABC([0-9] +)XYZ。*
例输入文件:
A
b
C
abc12345xyz
一个
b
C
像这样简单的声音,我无法弄清楚如何调用SED / AWK /呆子正确。我希望做的,是从我的bash脚本中有:
myvalue的= $(SED< ...什么...> input.txt中)
事情我已经尝试过包括:
的sed -e的/.*([0-9])* / \\\\ 1 / G'#example.txt的提取整个输入文件
SED -n的/.*([0-9])* / \\\\ 1 / G'#example.txt的没什么提取
我的 SED
键(Mac OS X)不与工作+
。我试图 *
,而不是和我说 P
打印匹配代码:
SED -n的/^.* ABC \\([0-9] * \\)XYZ。* $ / \\ 1 / P'example.txt文件
对于没有 +
匹配至少有一个数字字符,我会用:
SED -n的/^.* ABC \\([0-9] [0-9] * \\)XYZ。* $ / \\ 1 / P'example.txt文件
I see lots of examples and man pages on how to do things like search-and-replace using sed, awk, or gawk.
But in my case, I have a regular expression that I want to run against a text file to extract a specific value. I don't want to do search-and-replace. This is being called from bash. Let's use an example:
Example regular expression:
.*abc([0-9]+)xyz.*
Example input file:
a
b
c
abc12345xyz
a
b
c
As simple as this sounds, I cannot figure out how to call sed/awk/gawk correctly. What I was hoping to do, is from within my bash script have:
myvalue=$( sed <...something...> input.txt )
Things I've tried include:
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
My sed
(Mac OS X) didn't work with +
. I tried *
instead and I added p
tag for printing match:
sed -n 's/^.*abc\([0-9]*\)xyz.*$/\1/p' example.txt
For matching at least one numeric character without +
, I would use:
sed -n 's/^.*abc\([0-9][0-9]*\)xyz.*$/\1/p' example.txt
这篇关于如何使用sed,awk中,或只呆呆地看着是什么匹配打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!