我有运行python的bash函数(从stdin返回所有finded regex)
function find-all() {
python -c "import re
import sys
print '\n'.join(re.findall('$1', sys.stdin.read()))"
}
当我使用这个正则表达式find-all 'href="([^"]*)"' < index.html
时,它应该从正则表达式返回第一个组(来自文件index.html的href属性的值)
我怎样才能用sed或awk写这个?
答案 0 :(得分:3)
我建议您使用grep -o
。
-o, --only-matching
Show only the part of a matching line that matches PATTERN.
E.g:
$ cat > foo
test test test
test
bar
baz test
$ grep -o test foo
test
test
test
test
test
<强>更新强>
如果要从html文件中提取href属性,请使用如下命令:
$ grep -o -E 'href="([^"]*)"' /usr/share/vlc/http/index.html
href="style.css"
href="iehacks.css"
href="old/"
cut
但是你最好使用html / xml解析器来提高可靠性。
答案 1 :(得分:2)
这是一个gawk实现(未经其他awks测试):find_all.sh
awk -v "patt=$1" '
function find_all(str, patt) {
while (match(str, patt, a) > 0) {
for (i=0; i in a; i++) print a[i]
str = substr(str, RSTART+RLENGTH)
}
}
$0 ~ patt {find_all($0, patt)}
' -
然后:
echo 'asdf href="href1" asdf asdf href="href2" asdfasdf
asdfasdfasdfasdf href="href3" asdfasdfasdf' |
find_all.sh 'href="([^"]+)"'
输出:
href="href1"
href1
href="href2"
href2
href="href3"
href3
如果您只想打印已捕获的群组,请将i=0
更改为i=1
。使用i=0
即使您的模式中没有括号,也会得到输出。