【问题标题】:How to comment out python code using sed command如何使用 sed 命令注释掉 python 代码
【发布时间】:2015-07-15 01:35:36
【问题描述】:

我想使用 sed 命令注释掉以下代码行。

实际代码:

response = HttpResponse()
response['Content-Disposition'] = 'attachment; filename=%s.zip' % file_name.replace('.shp','')
response['Content-length'] = str(len(zip_stream))
response['Content-Type'] = mimetype
response.write(zip_stream)
return response

我想要什么:

#response = HttpResponse()
#response['Content-Disposition'] = 'attachment; filename=%s.zip' % file_name.replace('.shp','')
#response['Content-length'] = str(len(zip_stream))
#response['Content-Type'] = mimetype
#response.write(zip_stream)
#return response

唯一的问题是文件很大,到处都包含response,所以搜索应该根据上面提供的更具体。

给定的代码块位于特定文件的整个源代码的中间。

【问题讨论】:

  • 所以你想注释掉任何包含变量名response的行?你的问题不是很清楚。
  • 抱歉混淆了.. 不,我只是想注释掉提供的特定块,因为代码在各个地方都包含响应,我们可以使用响应来匹配它。从整个源代码中,我只想注释掉上面提到的块..
  • 那为什么不手动注释掉呢?否则 sed 没有模式(可以说)。
  • 所以你的问题不是批量替换什么的。它更像是如何找到你想要的块。而不是搜索“响应”,您是否尝试过搜索整行代码?例如"response['Content-Disposition'] = 'attachment; filename=%s.zip' % file_name.replace('.shp','')"?
  • 我正在开发Shell Script,它将是一个自动安装程序,用于安装一个相当复杂的开源项目。目前对于想要尝试的用户来说,没有任何简单的选择。

标签: python sed comments


【解决方案1】:

我对您在这里尝试做的事情做了一些假设。我假设您想在您选择的两行之间注释代码块。这是使用GNU sed的一种方式:

sed -i '/response = HttpResponse()/,/return response/s/.*/#&/' file.txt

【讨论】:

  • 非常感谢,它工作得很好..在测试文件上现在我将在我的实际代码上尝试它.. :)
  • @steve - 是的,它在实际代码上也运行良好.. :) 再次感谢您..
  • @Mebulo:没问题。很高兴我能帮忙:-)
【解决方案2】:
perl -i -ne 'if(/response = Http/../return response/){$_="#".$_}print' your_file

【讨论】:

    猜你喜欢
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    • 2011-02-03
    • 2017-10-20
    • 2010-10-15
    • 2014-06-08
    • 2011-08-07
    相关资源
    最近更新 更多