linux-命令sed 使用技巧

来源:互联网 发布:cf咪咕刷枪软件 编辑:程序博客网 时间:2024/06/05 10:09

本文主要讲解 sed  如何有效的处理文本,给文本在行首,行尾加一单引号. 

有时候我会希望我的文本前后都有单引号,这时候我该怎么做呢,sed 就是一个很好的工具。

1 在行首或者行尾 加字符

第一种写法

# 在行尾加 单引号sed "s/$/'/g"  1.txt # 在行首加单引号sed  "s/^/'/g"  1.txt


第二种写法

# 分别在行首和行尾加 HEAD,  TAILsed 's/^/HEAD&/g' 1.txt sed 's/$/&TAIL/g' 1.txt 


分别举例来看一下, 比如我的文本,是一段 文字。  

Technology is also not going to change who you choose to love.
同样科技也改变不了你的择偶对象。
I study the biology of personality, and I've come to believe that we've evolved four very broad styles of thinking and behaving,
我研究生物心理学,我开始相信人类已经进化出了四个广义的思考及行为方式,
linked with the dopamine, serotonin, testosterone and estrogen systems.
和多巴胺、血清素、睾丸激素和雌激素系统相关联。
So I created a questionnaire directly from brain science to measure the degree to which you express the traits
于是,基于脑科学原理我设计了一份问卷,用来衡量人们表达特征的程度,
the constellation of traits, linked with each of these four brain systems.
各种特征,与这四种大脑系统的关联性。
I then put that questionnaire on various dating sites in 40 countries.
我在40个国家的各种征婚网站上刊登了这份问卷。
Fourteen million or more people have now taken the questionnaire, and I've been able to watch who's naturally drawn to whom.
目前,已有1400多万人参与了问卷调查,我有幸可以观察那些天生相互吸引的人。






2 在行首,行尾 同时 加字符

有的人 可能 想到 -e 不就可以了吗 , 
# error 
sed  's/^/HEAD&/g'  -e  's/$/&TAIL/g'  1.txt  
实际上这样会有问题的,


解决方案 ,不用这个方法, 可以 这样来做

用下面的方法,可以解决

#  OK  在行首和行尾分别加 head he  tail sed '/./{s/^/HEAD&/;s/$/&TAIL/}' 1.txt#  OK  在行首和行尾分别加 head he  tail sed  '/./{s/^/Myhead---/;s/$/---Mytail/}'   1.txt


简单解释  sed  /./   双斜线中的点 ,就是代表任意字符, 可以认为是匹配每一行,之后,用{} 括起来,执行两次替换,^ 就是行首的意思, $就是行尾的意思,执行两次替换操作,搞定。


升级版的操作

#升级版  #在行首和行尾添加 相应内容sed  's/.*/Myhead&Mytail/' 1.txtsed  's/.*/Myhead&Mytail/' 1.txt

这里就是.* 是蛮力匹配,之后用&连接 你要添加的字符,字符串,就可以啦。



回到正题,如何给一行加入 行首单引号,行尾单引号

# 加行首和行尾 单引号sed  "s/.*/'&'/" 1.txt

注意这里 用 sed " s ///"  这里是为了避免和 插入的混淆,所以用了双引号。




如何删除 文中的单引号, 直接sed  替换就可以了

# 删除单引号
sed  -i  "s/'//g"  1.txt 

注意刚刚上述所说的加单引号,并没有修改1.txt ,只是打印出来,如果想要修改原文档, 请加 -i 选项。



                                        分享快乐,留住感动。      -----biaoge    2017年 12月 06日 星期三 23:06:38 CST

原创粉丝点击