【问题标题】:Search for string in text file and print line until next tab \t在文本文件中搜索字符串并打印行直到下一个标签 \t
【发布时间】:2017-05-23 03:23:45
【问题描述】:

我有一个相当复杂的文本文件file1.txt 没有被正确处理。然而,该文件是制表符分隔的,即每个字符串由\t 分隔。

我想编写一个脚本/使用一个 Unix 命令来解析整个文件中的某个字符串 string1:,它将打印冒号后面的行,直到在 \t 处停止。

文本文件如下所示:

...kjdafhldkhlfak\tSTRING1:Iwanttokeepthis\tfadfasdafldafh\tSTRING1:andthis\tafsdkfasldh....

所以grep like 函数输出

Iwanttokeepthis
andthis

在 Perl 中,我知道如果字符串与

一起出现,如何打印它
perl -wln -e 'print if /\bSTRING1\b/' file1.txt

如何修改它以打印STRING1:\t 之间的行?

【问题讨论】:

    标签: perl parsing grep string-matching


    【解决方案1】:

    使用 GNU grep:

    grep -Po 'STRING1:\K.*?(?=\t)' file
    

    输出:

    我想保留这个 和这个

    见:The Stack Overflow Regular Expressions FAQ

    【讨论】:

    • .*? 是一个脆弱的结构。您的特定模式没有问题,但我希望尽可能避免它。您也可以使用grep -Po 'STRING1:\K[^\t]*(?=\t)' file 或仅使用grep -Po 'STRING1:\K[^\t]*' file
    【解决方案2】:

    使用 Perl:

    $ echo $'kjdafhldkhlfak\tSTRING1:Iwanttokeepthis\tfadfasdafldafh\tSTRING1:andthis\tafsdkfasldh' > /tmp/file
    perl -lne 'while (/STRING1:([^\t]+)\t/g) {print $1}' /tmp/file
    Iwanttokeepthis
    andthis
    

    或者,如 cmets 中所述:

    $ perl -nle'print for /STRING1:([^\t]*)\t/g' /tmp/file
    Iwanttokeepthis
    andthis
    

    【讨论】:

    • 更简单的:perl -nle'print for /STRING1:([^\t]*)\t/g',或者只是perl -nle'print for /STRING1:([^\t]*)/g'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-20
    • 1970-01-01
    • 2015-09-11
    • 2015-11-12
    • 2014-09-06
    • 1970-01-01
    • 2015-02-13
    相关资源
    最近更新 更多