本文和大家分享的主要是linux中sed的使用,一起来看看吧,希望对大家学习linux有所帮助。 sed · sed可以基于输入到命令行的或是存储在命令文本文件中的命令来处理数据流中的数据。 · s命令会用斜线间指定的第二个文本字符串来替换第一个文本字符串。 echo "This is a test" | sed 's/test/big test/' #This is a big test · sed编辑器自身不会修改文本文件的数据,它只会将修改后的数据发送到STOUT · 在sed命令上执行多个命令时,只要用-e就可以了 sed -e 's/brown/green/; s/dog/cat/' date1 #将date1中brown替换成green,dog换成cat输出到STOUT -如果有大量要处理的sed命令,将它们放进一个文件中通常会方便一些 $ cat script1s/brown/green/s/dog/cat/ $ $ sed -f script1 data1 · p标记 sed -n 's/test/trial/p' data # -n选项禁止sed输出, p替换标记会输出修改过的行 · w标记,将输出保存的文件中 $ sed -n 's/test/trial/w test' data $ cat test This is a trial line · sed可以指定作用的行 sed '2s/dog/cat' data #作用到第2行 sed '2,3s/dog/cat' data #作用到第2,3行 sed '2,$s/dog/cat' data #作用到第2行到结尾行 sed '/Samantha/s/bash/csh' data #作用到匹配Samantha的行上 sed '/rich/s/bash/csh' /etc/passwd #找到含有rich的行,然后用csh替换文本bash · d命令可用于删除行(sed命令不会修改原始文件) sed 'd' data #删除data中所有行 sed '3d' data #删除第3行 sed '3,$d' data #删除第3行到最后一行 sed '/number 1/d' #删除匹配number 1的行 · i命令会在指定行前增加一个新行 · a命令会在指定的行后增加一个新行 · c命令会修改指定的行 · y命令用于当个字符的替换 sed `y/123/789/` data #data中的1替换成7,2替换成8,3替换成9 · r命令允许将一个独立文件中的数据插入到数据流中 $ cat data This is an added line. This is the second added line $ sed '3r data' test This is line number 1 This is line number 2 This is line number 3 This is an added line. This is the second added line This is line number 4 This is line number 5 This is line number 6 This is line number 7 多行命令 如果你正在数据中查找短语Linux System Administrators Group,很有可能短语在其中任意两个词之间被分成两行。如果你用普通的sed编辑器命令来处理文本,几乎不可能发现短语是怎么被分开的 & 符号用来代表替换命令的匹配模式 $ echo "The cat sleeps in his hat. " | sed 's/.at/"&"/g' The "cat" sleeps in his "hat". · 用圆括号来定义替换模式的子字符串,给第一个模块分配字符\1,第二个模块分配字符\2 $ echo "That furry cat is pretty" | sed 's/furry \(.at\)/\1/' That cat is pretty $ echo "That furry hat is pretty" | sed 's/furry \(.at\)/\1/' That hat is pretty · 使用包装脚本使用sed, 1!G表示将保持空间附加到模式空间,不附加到第一行文本后面,$p表示数据流到达最后一行时,打印 $ cat reverse.sh #!/bin/bash sed -n '{ 1!G h $p }' $1 $ cat data This is the header line. Linux System This is a data line.Linux System This is the last line. $ ./reverse.sh data System This is the last line. System This is a data line.Linux This is the header line. Linux · 格式化数据 cat format_number.sh #!/bin/bash result=`echo $1 | sed '{ :start s/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/ t start }'`echo $result $ ./format_number.sh 12345456 12,345,456 · 每两行之间添加一个空行 , /^$/d 删除空白行 $!G 任意行下添加空白行,除了最后一行 cat data This is one This is two This is three This is four $ sed '/^$/d;$!G' data This is one This is two This is three This is four · 给文件中的行编号 = 会输出行号 $ cat data1 This is one This is two This is three This is four $ sed '=' data1 | sed 'N;s/\n/ /' 1 This is one 2 3 This is two 4 5 This is three 6 7 This is four 来源:CSDN |
Linux学习之sed的使用
最新推荐文章于 2020-12-08 10:53:34 发布