Linux command to replace string in LARGE file with another string

前端 未结 7 758
终归单人心
终归单人心 2021-01-02 13:33

I have a huge SQL file that gets executed on the server. The dump is from my machine and in it there are a few settings relating to my machine. So basically, I want every oc

7条回答
  •  -上瘾入骨i
    2021-01-02 14:03

    sed is a good choice for large files.

    sed -i.bak -e 's%C://temp%//home//some//blah%' large_file.sql
    

    It is a good choice because doesn't read the whole file at once to change it. Quoting the manual:

    A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline). While in some ways similar to an editor which permits scripted edits (such as ed), sed works by making only one pass over the input(s), and is consequently more efficient. But it is sed's ability to filter text in a pipeline which particularly distinguishes it from other types of editors.

    The relevant manual section is here. A small explanation follows

    -i.bak enables in place editing leaving a backup copy with .bak extension

    s%foo%bar% uses s, the substitution command, which substitutes matches of first string in between the % sign, 'foo', for the second string, 'bar'. It's usually written as s// but because your strings have plenty of slashes, it's more convenient to change them for something else so you avoid having to escape them.

    Example

    vinko@mithril:~$ sed -i.bak -e 's%C://temp%//home//some//blah%' a.txt
    vinko@mithril:~$ more a.txt
    //home//some//blah
    D://temp
    //home//some//blah
    D://temp
    vinko@mithril:~$ more a.txt.bak
    C://temp
    D://temp
    C://temp
    D://temp
    

提交回复
热议问题