Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5741841
  • 博文数量: 675
  • 博客积分: 20301
  • 博客等级: 上将
  • 技术积分: 7671
  • 用 户 组: 普通用户
  • 注册时间: 2005-12-31 16:15
文章分类

全部博文(675)

文章存档

2012年(1)

2011年(20)

2010年(14)

2009年(63)

2008年(118)

2007年(141)

2006年(318)

分类:

2006-02-21 21:18:52

这些练习都来自和,我自己做了一下,并稍微做了一下解释,希望对大家学习有所帮助。

一. 任务:有一个样本hebing.txt,找到包含文字abcde的一行,并把这一行和下一行合并成一行.
CODE:  
$ cat hebing.txt
This is a test,
abcde
hello
ok
abcde
the botto
abcde
m.
This is a test,
abcde
hello
ok
abcde
the botto
abcde
m.
解决方法:

1.sed下一个命令
CODE:  
$ sed -e '/abcde/{N;s/\n/ /}' hebing.txt
This is a test,
abcde hello
ok
abcde the botto
abcde m.
This is a test,
abcde hello
ok
abcde the botto
abcde m.
2.awk实现
CODE:  
$ awk '{if(/abcde/){printf $0" ";next} else{print}}' hebing.txt
This is a test,
abcde hello
ok
abcde the botto
abcde m.
This is a test,
abcde hello
ok
abcde the botto
abcde m.
注意:上面用awk实现的使用的是printf不是print。



二. 任务:
把文件里的日期的写法从"年/月/日",改为
"日/月/年"。

比如说:1988/01/03,改写以后是:03/01/1988

文件如下:
CODE:  
0516001|uuu|0|0|0|1|1899/12/31|1899/12/31|2005/03/18|180|
0516001|uuu|0|0|0|1|1899/12/31|1899/12/31|2004/03/24|180|
0516001|uuu|0|1|0|0|2004/02/09|1899/12/31|1899/12/31|0|
要求对所有的日期都匹配,然后日期所在的位置是不定的
CODE:  
$ sed 's/\([0-9]\{4\}\)\/\([0-9]\{2\}\)\/\([0-9]\{2\}\)/\3\/\2\/\1/g' date.txt
0516001|uuu|0|0|0|1|31/12/1899|31/12/1899|18/03/2005|180|
0516001|uuu|0|0|0|1|31/12/1899|31/12/1899|24/03/2004|180|
0516001|uuu|0|1|0|0|09/02/2004|31/12/1899|31/12/1899|0|
解释:\n与模式中第n(单个数字)个 /(\) 指定的子字符串匹配,正则表达式在/(和\)之间的。


\([0-9]\{4\}\) 的正则表达式为 [0-9]\{4\},匹配连续4个数字。

\/ 匹配 \(反斜杠)。



三. 任务:删除文件中含有"[ ]"的行,中括号之间有一个空格
CODE:  
$ cat kuohao
{]
[] hsadfk
[ ] jsadfj
hfndh[]


$ sed '/\[ \]/d' kuohao
{]
[] hsadfk
hfndh[]


$ grep -v '\[ \]' kuohao
{]
[] hsadfk
hfndh[]
注意:[]要转义的。如果不转义的话。
CODE:  
$ sed '/[ ]/d' kuohao
{]
hfndh[]
四.
CODE:  
sed 's/modules\/\([^/ ]*\)\/*/\1.so/g'
输入modules/ppp 输出ppp.so


解释:模式空间的正则表达式为 modules\/\([^/ ]*\)\/.*

\(...\)
在此处表示确定...的内容将会被存放到一个地址中,以后想得到此出地址可用\x (x取决于之前是否有起同样作用的\(\)出现,如果有一个,那么x=2,如果没有x=1,以此类推)来获得

\/ 转义 / (反斜杠)

\([^/ ]*\) 匹配 [^/ ]*

[^/ ]表示 非/ 字符,[^/]表示 非/ 字符重复0或多次。

.* 匹配一串任意字符
阅读(1826) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~