【问题标题】:How to efficiently search/replace on a large txt file?如何有效地搜索/替换大型 txt 文件?
【发布时间】:2011-04-02 17:29:24
【问题描述】:

我有一个相对较大的 csv/文本数据文件 (33mb),我需要对其进行全局搜索并替换其上的分隔符。 (原因是似乎没有办法让 SQLServer 在表导出期间转义/处理数据中的双引号,但这是另一回事......)

我成功地在一个较小的文件上完成了 Textmate 搜索和替换,但它在这个较大的文件上卡住了。

似乎命令行 grep 可能是答案,但我不能完全掌握语法,唉:

grep -rl OLDSTRING . | xargs perl -pi~ -e ‘s/OLDSTRING/NEWSTRING/’

所以在我的例子中,我正在搜索 '^'(插入符号)字符并替换为 '"'(双引号)。

grep -rl " grep_test.txt | xargs perl -pi~ -e 's/"/^'

这不起作用,我假设它与转义双引号或其他东西有关,但我很迷茫。帮助任何人?

(我想如果有人知道如何让 SQLServer2005 在导出到 csv 期间处理文本列中的双引号,那真的可以解决核心问题。)

【问题讨论】:

    标签: regex sql-server-2005 perl csv grep


    【解决方案1】:

    您的 perl 替换似乎是错误的。试试:

    grep -rl \" . | xargs perl -pi~ -e 's/\^/"/g'
    

    解释:

    grep : command to find matches
    -r : to recursively search
    -l : to print only the file names where match is found
    \" : we need to escape " as its a shell meta char
    . : do the search in current working dir
    perl : used here to do the inplace replacement
    -i~ : to do the replacement inplace and create a backup file with extension ~
    -p : to print each line after replacement
    -e : one line program
    \^ : we need to escape caret as its a regex meta char to mean start anchor
    

    【讨论】:

    • 这既有效又有助于清楚地解释它。非常感谢!
    • 哦,好吧,我之前没有足够的“积分”来做到这一点。谢谢。
    【解决方案2】:
    sed -i.bak 's/\^/"/g' mylargefile.csv
    

    更新:你也可以按照 rein 的建议使用 Perl

    perl -i.bak -pe 's/\^/"/g' mylargefile.csv
    

    但在大文件上,sed 可能比 Perl 运行得快一点,因为我的结果显示在 600 万行文件上

    $ tail -4 file
    this is a line with ^
    this is a line with ^
    this is a line with ^
    
    $ wc -l<file
    6136650
    
    $ time sed 's/\^/"/g' file  >/dev/null
    
    real    0m14.210s
    user    0m12.986s
    sys     0m0.323s
    $ time perl  -pe 's/\^/"/g' file >/dev/null
    
    real    0m23.993s
    user    0m22.608s
    sys     0m0.630s
    $ time sed 's/\^/"/g' file  >/dev/null
    
    real    0m13.598s
    user    0m12.680s
    sys     0m0.362s
    
    $ time perl  -pe 's/\^/"/g' file >/dev/null
    
    real    0m23.690s
    user    0m22.502s
    sys     0m0.393s
    

    【讨论】:

    • 感谢您的帮助。我从未使用过 sed,但如果它如此简洁,它一定值得一看。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    • 2018-08-05
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多