sed命令中的替换(s、y)

上一篇 / 下一篇  2009-11-05 21:28:18 / 个人分类:shell脚本

函数参数 s 表示替换(substitute)文件内字串。其指令格式如下 :
[address1[ ,address2]] s/pattern/replacemen/[flag]
说明:
函数参数 s 最多与两个位址参数配合。
pattern: 它为 reguler expression 字串。它表示文件中要被替换的字串。

replacement: 它为一般字串。但其内出现下列字元有特别意义 :
& : 代表其前 pattern 字串。例如
sed -e 's/test/& my car/' test.txt
指令中 , & 代表 pattern字符串 "test";故执行後 , 文件中的第一个出现的 "test" 被替换成 "test my car"。
\n : 代表 pattern 中被第 n 个 \( 、\) 所括起来的字串。例如
sed -e 's/\(test\)\(my\)\(car\)/[\2 \3 \1]/' test.txt
指令中 , \1 表示 "test"、\2 表示 "my"、\1 表示 "car" 字串。故执行後 , 文件中的 "test my car" 被替换 成 "[my car test]"。
\ : 可用它来还原一些特殊符号(如上述的 & 与 \ )本身字面上的意义 , 或用它来代表换行 sed -e 's/hu\\a/zhou/g' test.txt就把hu\a替换成了zhou。
flag : 主要用它来控制一些替换情况 :
当 flag 为 g 时 , 代表替换所有符合(match)的字串 。
当 flag 为十进位数字 m 时 , 代表替换行内第 m 个符合的字串。
当 flag 为 p 时 , 代表替换第一个符合 pattern 的字串後 , 将该行再在原始行下面再输出一次。
当 flag 为 w wfile 时 , 代表替换第一个符合 pattern 的字串後 , 输出到 wfile 档内(如果 wfile 不存在 , 则会 重新开启名为 wfile 的档案)。
例:
题目 : 替换 input.dat 档内 "1996" 字串成 "1997" , 同时
将这些资料行存入 year97.dat 档内。
说明 : 用函数参数 s 指示 sed 将 "1996" 字串替换成 "1997" , 另外用 s argument 中的 flag w 指示 sed 将替换
过的资料行存入 year97.dat 档内。
sed 命令列:
sed -e 's/1996/1997/w year97.dat' input.dat  
当没有 flag 时 , 则将资料行内第一个符合 pattern 的字串以 replacement 字串来替换 。
delimiter标志字符(一般使用/) : 在 "/pattern/replace/[flag] " 中 "/" 被当成一 delimiter。除了空白(blank)、换行(newline) 之外 , 使用者可用任何字元作为 delimiter。例如下述编辑指令
s#/usr#/usr1#g
上述命令中 delimiter为#。如果用 "/" 做 delimiter , 则 sed 会将 pattern 与 replacement 中的 "/" 当成 delimiter 而发生错误。

address范围
sed -e '/find/s/replaced/replace/g' input.dat 意思是将输入文件中包含find字符串的行中的replaced替换成replace;
sed -e '/find1/,/find2/s/replaced/replace/g' input.dat
sed -e '1s/replaced/replace/g' input.dat 意思是将输入文件中第1行中的replaced替换成replace;
sed -e '1,3s/replaced/replace/g' input.dat
sed -e '1,/find2/s/replaced/replace/g' input.dat
sed -e '/find1/,1s/replaced/replace/g' input.dat

结合正则表达式:
 echo Tolstoy writes well | sed 's/Tolstoy/Camus/' 
结果为 Camus writes well;
 echo Tolstoy is worldly | sed 's/T.*y/Camus/'
结果为Camus,因为T.*y一直从第一个开始的T到最后一个y;
echo Tolstoy is worldly | sed 's/T[[:alpha:]]*y/Camus/'
结果为Camus writes well;
echo abc | sed 's/b*/1/'  替换第一个b*为1,结果问哦1abc;
echo abc | sed 's/b*/1/g'   替换是有的b*为1,结果问哦1a1bc1;

函数参数 y表示转换资料中的字元。其指令格式如下 :
sed -e '[address1[ ,address2]]y /xyz.../abc.../' input
对於上述格式有下面几点说明 :
函数参数最多配合两个位址参数。
指令中 , /abc.../xyz.../(x、y、z、a、b、c 代表某些字元) 为 y 的 argument 。其中 abc... 与 xyz... 的字元个数 必须相同。
sed 执行转换时 , 将 pattern space 内资料内的 a 字符转换成 x 字符 、b字符转换成 y 字符 、c 字符转换成 z字符 ...,替换是一一对应的关系,不在替换内容中的字符不会被替换。
例:
题目: 将 input.dat 档中的小写字母改成大写。假设 input.dat 档的内容如下 :
Sodd's Second Law:
Sooner or later, the worst possible set of
circumstances is bound to occur.
说明:利用函数参数 y 指示 sed 做字母大小的转换。
sed 命令列如下 :
sed -e ' y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/ ' input.dat
执行上述命令输出结果如下 :
SODD'S SECOND LAW:
SOONER OR LATER, THE WORST POSSIBLE SET OF
CIRCUMSTANCES IS BOUND TO OCCUR.


TAG: sed

 

评分:0

我来说两句

Open Toolbar