El uso e interpretación detallada del editor sed

El uso e interpretación detallada del editor sed

Uno, editor sed

Sed es un editor de flujo, el editor de flujo editará el flujo de datos según un conjunto de reglas proporcionadas de antemano antes de que el editor procese los datos.
El editor sed puede procesar los datos en el flujo de datos de acuerdo con los comandos, que se ingresan desde la línea de comandos o se almacenan en un archivo de texto de comandos

1. El flujo de trabajo de sed

(1), leer

sed lee una línea de contenido del flujo de entrada (archivo, canalización, entrada estándar) y la almacena en un búfer temporal (también conocido como espacio de patrón).

(2) Implementación

Por defecto, todos los comandos sed se ejecutan secuencialmente en el espacio del patrón. A menos que se especifique la dirección de la línea, el comando sed se ejecutará secuencialmente en todas las líneas.

(3), pantalla

Envíe el contenido modificado al flujo de salida. Después de enviar los datos, se borrará el espacio del patrón. Antes de que se procese todo el contenido del archivo, el proceso anterior se repetirá hasta que se procese todo el contenido.

Antes de que se procese todo el contenido del archivo, el proceso anterior se repetirá hasta que se procese todo el contenido.
Nota: De forma predeterminada, todos los comandos sed se ejecutan en el espacio del patrón, por lo que el archivo de entrada no cambiará de ninguna manera, a menos que se utilice la redirección para almacenar la salida.

2. Explicación del comando

命令格式:
sed -e '操作' 文件1 文件2 ...
sed -n -e '操作' 文件1 文件2 ...
sed -f 脚本文件 文件1 文件2 ...
sed -i -e '操作' 文件1 文件2 .

...

sed -e 'n{
操作1
操作2
...
}' 文件1 文件2 ...

Opciones comunes:

-e 或--expression=:表示用指定命令来处理输入的文本文件,只有一个操作命令时可省略,一般在执行多个操作命令使用
-f 或--file=:表示用指定的脚本文件来处理输入的文本文件。
-h 或--help:显示帮助。
-n、--quiet 或 silent:禁止sed编辑器输出,但可以与p命令一起使用完成输出。
-i:直接修改目标文本文件。

Operaciones comunes:

s:替换,替换指定字符。
d:删除,删除选定的行。
a:增加,在当前行下面增加一行指定内容。
i:插入,在选定行上面插入一行指定内容。
c:替换,将选定行替换为指定内容。
y:字符转换,转换前后的字符长度必须相同。
p:打印,如果同时指定行,表示打印指定行;如果不指定行,则表示打印所有内容;如果有非打印字符,则以 ASCII 码输出。其通常与“-n”选项一起使用。
=:打印行号。
l(小写L):打印数据流中的文本和不可打印的ASCII字符(比如结束符$、制表符\t)

Imprimir contenido:

sed -n -e 'p' test1.txt 

#不指定行 默认打印所有内容

[root@localhost ~]#sed -n -e 'p' test1.txt 
one
two
three
four
five
six
sed -n -e '='  test1.txt 

#打印文件内的行号

[root@localhost ~]#sed -n -e '=' test1.txt 
1
2
3
4
5
6
sed -n -e 'l'  test1.txt 

#打印文本和ASCII码

[root@localhost ~]#sed -n -e 'l' test1.txt 
one$
two$
three$
four$
five$
six$
sed -n -e '=;p'test1.txt 或
sed -n -e '=' -e 'p' test1.txt

sed -n '
> =
> p
> ' test1.txt
#打印文件中的文本和行号

[root@localhost ~]#sed -n -e '=;p' test1.txt 
1
one
2
two
3
three
4
four
5
five
6
six

(1) Dirección de uso:

El editor sed tiene 2 modos de direccionamiento:
1. Exprese el intervalo de línea en forma numérica
2. Utilice el modo de texto para filtrar las líneas

sed -n '1p' test1.txt    #打印第一行

[root@localhost ~]#sed -n '1p' test1.txt
one
sed -n '$p' test1       #打印最后一行

[root@localhost ~]#sed -n '$p' test1.txt
six
sed -n '1,3p' test1.txt   #打印1到3行

[root@localhost ~]#sed -n '1,3p' test1.txt 
one
two
three
sed -n '3,$p' test1.txt  #打印3行到最后一行

[root@localhost ~]#sed -n '3,$p' test1.txt 
three
four
five
six
sed -n '1,+3p' test1.txt   #打印1之后的连续3行,即1-4行

[root@localhost ~]#sed -n '1,+3p' test1.txt
one
two
three
four

s

ed '5q' test1.txt   #打印前5行信息后退出,q表示退出

[root@localhost ~]#sed '5q' test1.txt 
one
two
three
four
five
sed -n 'p;n' test1.txt   #打印奇数行(先从第一行打印,然后隔一行打印一次);n表示移动到下一行

[root@localhost ~]#sed -n 'p;n' test1.txt
one
three
five
sed -n 'n;p' test1.txt   		#打印偶数行 (先跳到第二行,然后打印,然后在跳过)

[root@localhost ~]#sed -n 'n;p' test1.txt
two
four
six
sed -n '2,${n;p}' test1.txt   #先跳到第二行,然后跳到下一行开始打印,从第三行开始打印奇数行

[root@localhost ~]#sed -n '2,${n;p}' test1.txt 
three
five
sed -n '/user/p' /etc/passwd    #打印/etc/passwd 文件内有user的行

[root@localhost ~]#sed -n '/user/p' /etc/passwd
saslauth:x:996:76:Saslauthd user:/run/saslauthd:/sbin/nologin
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin
usbmuxd:x:113:113:usbmuxd user:/:/sbin/nologin
qemu:x:107:107:qemu user:/:/sbin/nologin
radvd:x:75:75:radvd user:/:/sbin/nologin
sed -n '/^a/p' /etc/passwd     #打印以a开头的行

[root@localhost ~]#sed -n '/^a/p' /etc/passwd    
adm:x:3:4:adm:/var/adm:/sbin/nologin
abrt:x:173:173::/etc/abrt:/sbin/nologin
avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin
sed -n '/bash$/p' /etc/passwd  #打印以bash结尾的行

Inserte la descripción de la imagen aquí

sed -n '/ftp\|root/p' /etc/passwd  # 打印包含ftp或者root的行 

Inserte la descripción de la imagen aquí

sed -n '2,/nobody/p' /etc/passwd   #从第二行开始打印出第一个包含nobody的行

Inserte la descripción de la imagen aquí

Inserte la descripción de la imagen aquí

sed -n '/nobody/=’ /etc/passwd     #打印包含nobody的行号

Inserte la descripción de la imagen aquí

sed -nr '/ro{1,}t/p' /etc/passwd	#-r表示支持正则表达式
#匹配已ro开头,已t结尾,中间至少包含一个o的行

Inserte la descripción de la imagen aquí

(2), borre la línea

sed 'd' test.txt #全删

[root@localhost ~]#sed -i 'd' test.txt
[root@localhost ~]#cat test.txt 

sed '3d' test.txt # Elimina la tercera línea

[root@localhost ~]#sed '3d' test.txt
one 
two
four
five
six

siete #Puedes ver que la tercera línea se ha ido

sed '2,4d' test.txt # Eliminar 2 a 4 líneas

[root@localhost ~]#sed '2,4d' test.txt 
one 
five
six
seven   #可以看到234行都没有了
sed '$d' test.txt   #删除最后一行

[root@localhost ~]#sed '$d' test.txt
one 
two
three
four
five
six   #第七行seven没有了
sed '/^$/d' .test.txt    #删除空行

Inserte la descripción de la imagen aquí

sed '/bash$/d' /etc/passwd    #删除已bash结尾的行

Inserte la descripción de la imagen aquí

sed '/nologin$/!d' /etc/passwd		#“!”表示取反操作  不删除nologin结尾的行,也就是除了nologin结尾的行都删除

Inserte la descripción de la imagen aquí

sed '/2/,/3/d' test.txt		#从第一个位置打开行删除功能,到第二个位置关闭行删除功能
sed '/1/,/3/d' test.txt

Inserte la descripción de la imagen aquí

(3) Reemplazar

行范围 s/旧字符串/新字符串/替换标记

4 tipos de etiquetas de reemplazo:

数字:表明新字符串将替换第几处匹配的地方
g:表明新字符串将会替换所有匹配的地方
p:打印与替换命令匹配的行,与-n一起使用
w 文件:将替换的结果写到文件中
sed -n 's/root/admin/p' /etc/passwd   #把root替换成admin 默认第一个root

Inserte la descripción de la imagen aquí
Inserte la descripción de la imagen aquí

sed -n 's/root/admin/2p' /etc/passwd  #把每一行的第二个root替换成admin

Inserte la descripción de la imagen aquí

sed -n 's/root/admin/gp' /etc/passwd   #把root全部替换成admin

Inserte la descripción de la imagen aquí

sed 's/root//g' /etc/passwd            #把所有的root换成空,就是删除的意思

Inserte la descripción de la imagen aquí

sed '1,20 s/^/#/' /etc/passwd          #在1-20行的行首添加#号

Inserte la descripción de la imagen aquí

sed '/^root/ s/$/#/' /etc/passwd       #找到root开头的行,在结尾加上#

Inserte la descripción de la imagen aquí

sed '1,20w out.txt' /etc/passwd         #把1-20行输出保存到out.txt文件内
sed '1,20 s/^/#/w out.txt' /etc/passwd  #把1-20行的开头加上#号 输出到out.txt文件内

```handlebars
sed -n 's/\/bin\/bash/\/bin\/csh/p' /etc/passwd  #
sed -n 's!/bin/bash!/bin/csh!p' /etc/passwd		#使用“!”作为字符串分隔符
把bash替换成csh

Inserte la descripción de la imagen aquí

sed '/three/c ABC' test.txt#搜索到包含45的行,整行替换成ABC

Inserte la descripción de la imagen aquí

sed '/3/ y/3/A/' test.txt    #搜索到3的行,把3替换成相同字符串长度的A

Inserte la descripción de la imagen aquí

sed '1,3a ABC' testfile2       # 1-3行下面分别插入ABC

Inserte la descripción de la imagen aquí

sed '1i ABC' test.txt       #1行上面加ABC

Inserte la descripción de la imagen aquí

sed '5r /etc/resolv.conf' test.txt      # /etc/resolv文件导入test第五行

Inserte la descripción de la imagen aquí

sed '/root/{H;d};$G' /etc/passwd	#将包含root的行剪切到末尾,H表示复制到剪切板,G表示粘贴到指定行后

Inserte la descripción de la imagen aquí

Inserte la descripción de la imagen aquí

sed '1,5H;15G' /etc/passwd    #把1-5行复制到15行后面

Inserte la descripción de la imagen aquí

Supongo que te gusta

Origin blog.csdn.net/weixin_51573771/article/details/111801666
Recomendado
Clasificación