且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Linux命令用另一个字符串替换字符串中的大文件

更新时间:2023-02-12 18:26:51

SED 是一个对于大文件不错的选择。

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:

一个流编辑器,用于执行
  在输入基本的文本转换
  从流(文件或输入
  管道)。虽然在某些方面很相似
  要允许脚本编辑器
  编辑(如ED),SED作品
  使得只有一个传过来的
  输入(多个),并且是因此更
  高效。但它是sed的能力
  在管道过滤器案文
  特别是它区别
  其他类型的编辑。

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能够到位编辑留下一个备份副本.bak扩展

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

S%富%的酒吧%用途秒,替换命令,该命令
  首先替换字符串匹配
  在%符号,'富',第二间
  字符串'吧。它通常写为s //
  但是因为你的字符串有充足
  斜线,它更方便
  改变他们别的东西,所以你
  避免逃避它们。

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.

示例


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