使用grep或sed在文件中提取特定模式

时间:2015-09-29 09:12:01

标签: bash sed grep

我有以下文件:

esdf http://x.com/dfsdfg&%^*
dsfdfg http://x.com/dgfhfgh
dfgdfg http://x.com/
dfgdg http://x.com/fghfgh#!
dfgdg http://x.com/fghfghfghj
rdfdre http://x.com/jkljlklkj
rdfg http://x.com/kjhjkj
rfdfg http://x.com/kjlkj
drfgdfdghttp://x.com/jklkjljkl
dfgdfgd http://x.com/jkljkl
http://x.com/jklkjl
http://x.com/jkkjljkljkl

我想从http://x.com/开始提取所有字符串。

我尝试的是:

grep -o http://x.com/[a-zA-Z0-9]* file.txt

但结果不是我想要的。我该怎么做特殊字符

更新

我不知道我应该用特殊字符做什么。您看到第一行是esdf http://x.com/dfsdfg&%^*。当我运行命令时,输出是http://x.com/dfsdfg但我希望打印http://x.com/dfsdfg&%^*

我想要这个输出:

http://x.com/dfsdfg#$^
http://x.com/dgfhfgh#$&&*
http://x.com/
http://x.com/fghfgh
http://x.com/fghfghfghj
http://x.com/jkljlklkj
http://x.com/kjhjkj
http://x.com/kjlkj
http://x.com/jklkjljkl
http://x.com/jkljkl
http://x.com/jklkjl
http://x.com/jkkjljkljkl

2 个答案:

答案 0 :(得分:1)

您的角色类[a-zA-Z0-9]仅匹配您在此处列出的字符。如果要匹配更多字符,请列出更多字符。

grep -o 'http://x\.com/[-^#!?&%$*_a-zA-Z0-9]*' file.txt

因为&*对shell有特殊含义,所以需要引用正则表达式。 (无论如何,这一般都是个好主意。)

甚至可能一直走到任何非空白的地方:

grep -o 'http://x\.com/[^[:blank:]]*' file.txt

或者,如果匹配模式总是延伸到行尾,只需

grep -o 'http://x\.com/.*' file.txt

在字符类中,除了范围运算符-,否定^和终结符]之外,每个字符只匹配自身。如果要将它们包含在字符类中,则需要将它们放在第一位,除了否定之外,当它是不是类中的第一个字符时,它会匹配。命名的POSIX类[:blank:][:alnum:]等使问题稍微复杂化。

答案 1 :(得分:0)

简单地:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

string DeriveFQN<T>(Expression<Func<T>> p)
    {
        var mbr = ((MemberExpression)p.Body).Member;
        var fqn = string.Format("{0}.{1}", mbr.DeclaringType.FullName, mbr.Name);

        return fqn;
    }

grep -o 'http://x\.com/.*' inputfile 会将所有字符与该行的末尾匹配。