Pau*_*omé 23 performance sed text-processing
Given a string composed of 0
s and 1
s, my goal is to replace 0 by 1 and vice-versa. Example:
Input
111111100000000000000
Run Code Online (Sandbox Code Playgroud)
Intended output
000000011111111111111
Run Code Online (Sandbox Code Playgroud)
I tried, unsuccessfully, the following sed
command
echo '111111100000000000000' | sed -e 's/0/1/g ; s/1/0/g'
000000000000000000000
Run Code Online (Sandbox Code Playgroud)
What am I missing?
Ste*_*itt 62
您可以tr
为此使用,其主要目的是字符翻译:
echo 111111100000000000000 | tr 01 10
Run Code Online (Sandbox Code Playgroud)
您的sed
命令将所有 0 替换为 1,从而生成仅包含 1 的字符串(原始 1 和所有替换的 0),然后将所有 1 替换为 0,从而生成仅包含 0 的字符串。
在长流上,tr
比sed
; 对于 100MiB 文件:
$ time tr 10 01 < bigfileof01s > /dev/null
tr 10 01 < bigfileof01s > /dev/null 0.07s user 0.03s system 98% cpu 0.100 total
$ time sed y/10/01/ < bigfileof01s > /dev/null
sed y/10/01/ < bigfileof01s > /dev/null 3.91s user 0.11s system 99% cpu 4.036 total
Run Code Online (Sandbox Code Playgroud)
ste*_*ver 40
虽然tr
是这项工作的正确工具,但您可以sed
使用y
(transliteration) 命令而不是s
(substitution) 命令来完成它:
$ echo '111111100000000000000' | sed 'y/01/10/'
000000011111111111111
Run Code Online (Sandbox Code Playgroud)
y
基本上sed
是tr
-的内部实现- 包含所有隐含的开销。
abo*_*uso 13
一种方式是 echo "111111100000000000000" | sed 's/1/2/g;s/0/1/g;s/2/0/g'