[英]Edit a text file line by line in bash
我有一個requirements.txt
文件,其中包含以下幾行:
PyMySQL==0.9.3
botocore==1.12.196
boto3==1.9.188
我需要使用bash就地編輯此文件,以刪除所有包含boto3
和botocore
。 到目前為止,我想出了-
while read a ; do echo ${a//boto3==1.9.188/} ; done < requirements.txt > requirements.txt.t ; mv requirements.txt{.t,}
..成功刪除了包含boto3==1.9.188
的行。 但是,此版本號可以是任何東西,例如1.10.122
。
如何概括上面的腳本以刪除包含boto3
和botocore
字符串的所有行? 還是有更好的方法來做到這一點? 謝謝。
grep -vE '^(botocore|boto3)\W' requirements.txt > requirements.txt.new && \
mv requirements.txt.new requirements.txt
說明:
-v
告訴grep輸出與模式不匹配的輸出行,並跳過確實匹配的行。 -E
告訴grep允許擴展的正則表達式,我們將其用於替換。 ^
將模式錨定到行的開頭,以使其與foobotocore==1.2.3
不匹配。 (x|y)
構造匹配x
或y
。 (要添加第三個包,只需添加另一個|
以創建(x|y|z)
。) \\W
匹配“非單詞字符”,因此模式不匹配botocorefoo==1.2.3
。 &&
僅在grep
成功並且至少匹配一行時才調用mv
命令(防止破壞整個文件)。 使用awk
awk '!/(botocore|boto3)/' requirements.txt > requirements.txt.t && mv requirements.txt.t requirements.txt
使用ed
:
printf 'g/botocore/d\ng/boto3/d\nwq\n' | ed requirements.txt
ed
工作方式是從標准輸入中讀取一組命令(以換行符終止),並將它們應用於以其參數命名的文件。 該命令應該看起來很熟悉,如果你熟悉sed
(事實上, sed
是A S tream基於ED itor ed
)。
g/botocore/d
選擇與正則表達式botocore
匹配的每一行,並對每行應用d
(刪除)命令。 g/boto3/d
對於匹配boto3
行boto3
。 wq
保存更改和引號。 使用perl:
在這種情況下,我喜歡perl,因為
命令:
$ perl -ni -e '/\b(boto3|botocore)\b/ || print;' requirements.txt
選項明細
/ \\ b(boto3 | botocore)\\ b / || 打印;
如果行與boto3或botocore的單詞不匹配,則會讀取此內容,然后打印。 \\ b表示單詞邊界。
例:
$ cat requirements.txt
PyMySQL==0.9.3
botocore==1.12.196
boto3==1.9.188
$ perl -ni -e '/\b(boto3|botocore)\b/ || print;' requirements.txt
$ cat requirements.txt
PyMySQL==0.9.3
$
備份名為“ requirements.txt.orig”的文件的示例
$ cat requirements.txt
PyMySQL==0.9.3
botocore==1.12.196
boto3==1.9.188
$ perl -ni.orig -e '/\b(boto3|botocore)\b/ || print;' requirements.txt
$ cat requirements.txt
PyMySQL==0.9.3
$ cat requirements.txt.orig
PyMySQL==0.9.3
botocore==1.12.196
boto3==1.9.188
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.