簡體   English   中英

python中的sed命令

[英]Sed command in python

我的輸入是

Type combinational  function (A B)

希望輸出是

Type combinational 
function (A B)

我使用了代碼及其工作

sed 's/\([^ ]* [^ ]*\) \(function.*\)/\1\n\2/' Input_file

當我使用使用此代碼python腳本中os.systemsubprocess及其給我錯誤。 我如何在 python 腳本中執行這個sed 或者我如何為上面的sed code編寫 python sed code 使用的 Python 代碼

cmd='''
sed 's/\([^ ]* [^ ]*\) \(function.*\)/\1\n\2/' Input_file
'''
subprocess.check_output(cmd, shell=True)

錯誤是

sed: -e expression #1, char 34: unterminated `s' command 

字符串中的\\n被 Python 替換為文字換行符。 正如@bereal 在評論中所建議的那樣,您可以通過在腳本周圍使用r'''...'''而不是'''...'''來避免這種情況; 但是更好的解決方案是避免在sed做 Python 本身已經做得很好的事情。

with open('Input_file') as inputfile:
   lines = inputfile.read()
lines = lines.replace(' function', '\nfunction')

這比您當前的sed腳本稍微sed ,因為它不需要在function標記之前正好有兩個空格分隔的標記。 如果你想嚴格一點,試試re.sub()

import re
# ...
lines = re.sub(r'^(\S+\s+\S+)\s+(function)', r'\1\n\2', lines, re.M)

(切線地,您還想避免不必要的shell=True ;也許請參閱子進程中 'shell=True' 的實際含義

盡管解決方案 1 和 2 是讓您的代碼運行(在 Unix 上)的最短有效方法,但我想添加一些備注:

一種。 os.system() 有一些與之相關的問題,應該替換為 subprocess.call("your command line", shell=False)。 無論使用 os.system 還是 subprocess.call,shell=True 都意味着存在安全風險。

由於 sed(和 awk)是嚴重依賴正則表達式的工具,因此在構建 python 以實現可維護性時,建議使用本機 python 代碼。 在這種情況下,請使用 re 正則表達式模塊,該模塊具有 regexp 優化實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM