sed文本替换

很多shell 通过grep取出文本, 正则替换再输出。

正确的是sed。

通过s 命令: 

   echo Tom like Jerry. Tom hats Jerry. > kan.txt

  sed 's/Tom/Kan' < kan.txt

  Kan like Jerry. Tom hats Jerry.

设置g,全局替换。 没有设置的话,只替换第一个。指定n 取代第n个。

sed 's/Tom/Kan/g'  kan.txt

Kan like Jerry. Kan hats Jerry.

 sed 's/Tom/Kan/2'   kan.txt

 Tom like Jerry.Kan hats Jerry.

 here the kan.txt has not been changed, if we want to change the kan.txt;

we needs to use 

sed -i  "" 's/Tom/Kan/g' kan.txt

The OS X version needs a value for the -i flag so you don’t inadvertently overwrite a file if you don’t mean to. To overwrite the file we’re trying to modify you just need to add two speech marks after the -i flag as follows.

(be careful, only we change the old file, we can not change it back)

 

 

http://redhat-linux4u.blogspot.com/2018/03/sed_24.html

 

 

 

 

https://www.cnblogs.com/ctaixw/p/5860221.html

this link is very useful.

note:

using sed is enough, using awk is not needed.

 

posted @ 2020-05-19 13:34  John_K  阅读(341)  评论(0)    收藏  举报