terminate.jpg

首页

技术分享

神奇的sed命令

从文件删除指定的行

sed -i '192,193d' scripts/model_migrations.py

sed

将文件内容插入到另一个文件的指定位置

origin.txt

abc
defc
ssss
add.txt
hello this is last line

add.txt

from custom_fields.myfield import MyField
def render_item(type_, obj, autogen_context):
"""Apply custom rendering for selected items."""

if type_ == 'type' and isinstance(obj, MyField):
autogen_context.imports.add("from custom_fields import myfield")
return "myfield.%r" % obj

# default rendering for other objects
return False

执行如下命令

sed -i '/# ... etc./r add.txt' origin.txt

结果

abc
defc
ssss
from custom_fields.myfield import MyField
def render_item(type_, obj, autogen_context):
"""Apply custom rendering for selected items."""

if type_ == 'type' and isinstance(obj, MyField):
autogen_context.imports.add("from custom_fields import myfield")
return "myfield.%r" % obj

# default rendering for other objects
return False
hello this is last line

插入一行到文件指定的位置

还是上面的origin,txt,执行如下命令

sed '/ssss/ a insert line' origin.txt
# 结果
abc
defc
ssss
insert line
hello this is last line


#如果想要插入到指定行的上一行,只要把a 改成i
sed '/ssss/ i insert line' origin.txt
# 结果
abc
defc
insert line
ssss
hello this is last line

Comments:

captcha