2009年1月9日星期五

初学sed

sed, awk等等UNIX下的工具初看显得晦涩又难用,就些命令行搞那么复杂干哈子呀。

不过一旦掌握以后就能发现给日常操作带来很大好处,那些简洁高效的命令行可都有着悠久 的历史了……

因此在学习他们之前,告诫自己:Don't get confuSed~

这里的例子全部来自ibm developerworks。
http://www.ibm.com/developerworks/linux/library/l-sed1.html

# 基本篇
sed -e 'd' /etc/services #删除所有行,因此没有输出
sed -e '1d' /etc/services | more #删除第一行
sed -e '1,10d' /etc/services | more #删除1-10行

# 正则篇
sed -e '/^#/d' /etc/services | more #删除注释
sed -n -e '/regexp/p' /path/to/my/test/file | more #打印匹配regexp的行
#-n 标示只打印regexp匹配字符,-e针对文本,-f将指定sed 脚本

#标准的正则符号有
# ^: matches all begin with...
# $: matches the end of the line...
# .: matches any single char
# *: will match zero or more occurences of the previous char
# []: matches all the characters inside the []

sed -n -e '/BEGIN/,/END/p' /my/test/file | more
#打印一个范围,首行包含BEGIN, 尾行包含END

sed -ne '/main[[:space:]]*(/,/^)/p' tmp.c
#打印main函数

# 替换篇
sed -e 's/foo/bar/' myfile.txt #找到第一个foo,替换为bar
sed -e 's/foo/bar/g' myfile.txt #全局替换
sed -e '1,10s/foo/bar/g' myfile.txt
sed -e '/^$/,/^END/s/foo/bar/g' myfile.txt
#以最前的空行为开始,END字符结束

sed -e 's:/usr/local:/usr:g' myfile.txt
#改变操作服为`:'

sed -e 's/<[^>]*>//g' myfile.html
#原文本: This is what I want
#改变后: This is what I want.

sed -e 's/.*/ralph said: &/' myfile.html
#在所有首行添加"ralph said: "

sed -e 's/\(.*\) \(.*\) \(.*\)'/Victor \1-\2 Von \3/' myfile.txt
#原文本:
# foo bar oni
# eeny meeny miny
#改变后:
# Victor foo-bar Von oni
# Victor eeny-meeny Von miny


sed一般用来 (via builder.com)—

  • Double/triple-space a file
  • 转化DOS/UNIX 的新行(newline)
  • 删除前后的空格
  • 在所有/全部行上进行取代操作
  • 删除连续的空行
  • 删除文件开头和结尾的空行

没有评论:

发表评论