文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>sed学习笔记(六)--总结与一行脚本

sed学习笔记(六)--总结与一行脚本

时间:2007-12-21  来源:kinwin

首先还是sed的工作流程
sed maintains two data buffers: the active pattern space, and the auxiliary hold space. Both are initially empty. sed operates by performing the following cycle on each lines of input: first, sed reads one line from the input stream, removes any trailing newline, and places it in the pattern space. Then commands are executed; each command can have an address associated to it: addresses are a kind of condition code, and a command is only executed if the condition is verified before the command is to be executed. When the end of the script is reached, unless the -n option is in use, the contents of pattern space are printed out to the output stream, adding back the trailing newline if it was removed.Then the next cycle starts for the next input line. Unless special commands (like `D') are used, the pattern space is deleted between two cycles. The hold space, on the other hand, keeps its data between cycles (see commands `h', `H', `x', `g', `G' to move data between both buffers).
sed默认是在所有的命令执行完后输出当前pattern space的内容。用n选项可以跳过这一步。
一些直接输出的命令:
p    输出当前pattern space中的内容
l    同p,但是也会显示一些控制字符
=    直接输出当前行号
q,n  默认输出当前pattern space的内容,用n选项可以跳过
w file  输出pattern space到file

a,i和c在处理两地址范围时的不同处理方式
小写和大写
一般小写表示覆盖,大写表示追加
小写针对全体,大写针对第一行
pattern space每次循环都会刷新。hold space具有记忆功能。

一些一句话sed脚本
统计行数(wc -l)
sed -n '$='
反转行序(tac)
sed -n '1!G;$p;h'
反转一行的字符顺序
sed '/\n/!G;s/\(.\)\(.*\n\)/&\2\1/;//D;s/.//'

 sed 's/^.*$/\n&\n/;:x s/\(\n.\)\(.*\)\(.\n\)/\3\2\1/;tx;s/\n//g'
经实验,第二种方法效率更高。可以用time试一下
输出奇数行
sed 'n;d'

sed -n '1~2p'

sed -n 'N;P'

sed 'x;$!N;x'
给每一行加上行号
sed '=' filename | sed 'N;s/\n/\t/'
给非空行加行号
sed '/./=' filename | sed '/./N;s/\n/\t/'
显示一个文件最后5行
sed -e :a -e '$q;N;6,$D;ba'
相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载