在我刚接触Linux的那段时间,参加了一个面试其中有一道面试题没做出来,这道题一直烙在我脑海,面试完之后我便开始认真的学了一下sed,轻松决解。
面试题内容大致如下:
1.用sed将 one 1 转变为 one 1
two 1 two 2
three 1 three 3
four 1 four 4
文件名:test.txt
sed “=” test.txt | sed “N;s/ / /;s/(. )(.*)( 1)/21/”
执行过程:sed的"="选项为显示行号:
sed -i "=" test.txt
1 one 1 2 two 1 3 three 1 4 four 1
n 输出模式空间行,读取下一行替换当前模式空间的行,执行下一条处理命令而非第一条命令。
N 读入下一行,追加到模式空间行后面,此时模式空间有两行,并用换行符分隔。
h 把模式空间里的行拷贝到暂存空间。
H 把模式空间里的行追加到暂存空间。
g 用暂存空间的内容替换模式空间的行。
G 把暂存空间的内容追加到模式空间的行后。
x 将暂存空间的内容于模式空间里的当前行互换。
sed -i "N;s/ / /;s/(. )(.*)(1)/21/" test.txt
N:
模式空间:
1 one 1 2 two 1 3 three 1 4 four 1
s/ / /:
1 one 1 2 two 1 3 three 1 4 four 1
s/(. )(.*)(1)/21/:
one 1 two 2 three 3 four 4
2.奇数行插入一个空行,偶数行插入两个空行
sed '1~2!G' info.txt | sed '/^$/!G'
3.统计域名
文本:
http://www.baidu.com/more/ http://www.baidu.com/guding/more.htmlhttp://www.baidu.com/events/20060105/photomore.htmlhttp://hi.baidu.com/browse/http://www.sina.com.cn/head/www20021123am.shtmlhttp://www.sina.com.cn/head/www20041223am.shtml
[root@docker1 test]# sed 's/http:/// /g' yunm.txt | sed '/^$/d' |awk -F/ '{print $1}' | sort | uniq -c | sort -r 3 www.baidu.com 2 www.sina.com.cn 1 hi.baidu.com