带有多个表达式的 sed 与带有分号的一个表达式相同吗? [英] Is sed with multiple expressions the same as one expression with semi-colons?

查看:35
本文介绍了带有多个表达式的 sed 与带有分号的一个表达式相同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常大的文件,其中有多个 sed 命令可以运行,我想避免内存不足错误并节省时间.这些都是等价的吗?

I have a very large file with multiple sed commands to run on it, and I want to avoid out-of-memory errors and save time. Are these all equivalent?

  1. sed -e 'expr1' -e 'expr2' -e 'expr3' 文件
  2. sed 'expr1;expr2;expr3' 文件
  3. sed expr1 文件 |sed expr2 |sed expr3

我的猜测是,通过 (3) 中的管道,每次都单独处理流,因此与仅处理一次的 (2) 相比,它需要 3 倍的时间.但我不确定 sed 内部如何处理 (1).

My guess is that with piping in (3), the stream is processed separately each time, so it would take 3x as long as compared to (2) where it is only processed once). But I am not sure how sed internally processes (1).

推荐答案

首先,sed -e 'expr1' -e 'expr2' filesed 'expr1; 完全一样;expr2'文件.同样等价的是

Firstly, sed -e 'expr1' -e 'expr2' file is exactly the same as sed 'expr1;expr2' file. Also equivalent are

sed 'expr1
expr2' file

和存储

expr1
expr2

(or expr1;expr2) 在一个文件中,例如 sedscr 并用 sed -f sedscr file 调用它,或者最终存储

(or expr1;expr2) in a file, e.g., sedscr and calling it with sed -f sedscr file, or finally storing

/usr/bin/sed -f

expr1
expr2

在文件 sedscr 中并用 ./sedscr file 调用它.

in a file sedscr and calling it with ./sedscr file.

对于每个输入行,sed 会遍历完整的脚本并将所有命令应用于它,然后转到下一个输入行.

For each input line, sed goes through the complete script and applies all commands to it, then goes to the next input line.

另一方面,管道 sed 调用每次都通过 sed 遍历整个文件(并为每个调用创建一个子外壳).如果你对每一行都做一个操作,这可能不会有太大的不同,但是想象一下一个相互依赖的替换链,比如一个文件

Piping sed calls, on the other hand, has sed go through the whole file each time (and creates a subshell for each call). This might not make a big difference if you do an operation on every line, but imagine a chain of substitutions that depend on each other, like for a file

xx
xx
pattern
xx
xx
PATTERN
xx
xx

并且您希望以不区分大小写的方式将大写 PATTERN 放在括号中,无论您在哪里找到它.如果你像这样使用管道

and you want, in a case insensitive manner, end up with uppercase PATTERN in parentheses wherever you find it. If you use pipes as in

sed 's/pattern/PATTERN/' infile | sed 's/PATTERN/(&)/'

您对文件进行了两次检查,总共进行了三个操作:

you go through the file twice for three operations in total:

Initial  1st pass 2nd pass
xx       xx       xx
xx       xx       xx
pattern  PATTERN  (PATTERN)
xx       xx       xx
xx       xx       xx
PATTERN  PATTERN  (PATTERN)
xx       xx       xx
xx       xx       xx

但与

sed 's/pattern/PATTERN/;s/PATTERN/(&)/' infile

您只需通过一次即可获得相同的结果.所以,无论如何,试着把所有东西都塞进一个单一的命令中.

you get the same result in just one pass. So, by all means, try and cram everything into a single command.

GNU sed 可以在一个命令中完成:sed 's/pattern/\U(&)/' infile.

这篇关于带有多个表达式的 sed 与带有分号的一个表达式相同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆