LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 942|回复: 3

有没有SED高手,帮我注释一段小代码吧

[复制链接]
发表于 2004-11-17 11:41:31 | 显示全部楼层 |阅读模式
#!/bin/sh

while read old

do

        new=`echo $old|sed '

        h

        s:.*/::

        s: :_:g

        G

        s:\(.*\)\n\(.*/\).*:\2\1:'`

        mv "$old" "$new"

done

上面的代码是用来将文件名中的空格替换成_的,但是具体的一行一行代码看不懂,望高手指点一下!!!!!!!
发表于 2004-11-17 14:32:29 | 显示全部楼层
h
===>把文件中的空格hold
s:.*/::
===>相当于把/home/yourname/filename hello替换成filename hello
s: :_:g
===>把空格替换成_,filename hello变成filename_hello
G
===>增加一行,变成
filename_hello
/home/yourname/filename_hello
s:\(.*\)\n\(.*/\).*:\2\1:
===>\(.*\)对应\2,换行符前的任意多字符,\(.*/\)对应\1,即第二行的/home/yourname/


PS:希望有说清楚,对你有帮助。不妨自己实验
     如:echo "/home/yourname/filename hello"|sed 'h'
            echo "/home/yourname/filename hello"|sed 'h;s:.*/::'
 楼主| 发表于 2004-11-17 14:54:12 | 显示全部楼层
3x a lot
 楼主| 发表于 2004-11-17 17:00:17 | 显示全部楼层
翻阅了一下《sed&awk》那本书,结合freefall的帖子,这里给出自己的一点体会,希望各位指正。
h
=======>The hold command copies the current input line into the hold space.
Pattern space:/home/yourname/filename hello
Hold space:/home/yourname/filename hello
s:.*/::
===>相当于把/home/yourname/filename hello替换成filename hello
Pattern space:filename hello
Hold space:/home/yourname/filename hello
s: :_:g
===>把空格替换成_,filename hello变成filename_hello
Pattern space:filename_hello
Hold space:/home/yourname/filename hello
G
====>The Get command appends the line saved in the hold space to the pattern space.
Pattern space:
filename_hello\n/home/yourname/filename hello
Hold space:/home/yourname/filename hello
s:\(.*\)\n\(.*/\).*:\2\1:
==>对上面产生的Pattern space进行替换操作
第一个\(.*\),也就是see section,对应filename_hello
第二个\(.*/\),对应/home/yourname/
2,1组装,结果/home/yourname/filename_hello

总结一下,sed有两个缓存空间,一个是pattern space,一个是hold space.所有的s操作是针对pattern space来进行的。还有一个就是see section的概念,它是用\(see section)\来定义的。哈哈,研究了一天终于写出这点东西,看来要明白sed,最好的资料还是sed & awk, 2nd Edition,这里有下载ftp://210.73.95.87/books/unix/O'Reilly%20-%20Sed%20&%20awk,%202nd%20Edition.rar。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表