簡體   English   中英

在bash中逐行編輯文本文件

[英]Edit a text file line by line in bash

我有一個requirements.txt文件,其中包含以下幾行:

PyMySQL==0.9.3
botocore==1.12.196
boto3==1.9.188

我需要使用bash就地編輯此文件,以刪除所有包含boto3botocore 到目前為止,我想出了-

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

如何概括上面的腳本以刪除包含boto3botocore字符串的所有行? 還是有更好的方法來做到這一點? 謝謝。

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)構造匹配xy (要添加第三個包,只需添加另一個|以創建(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對於匹配boto3boto3
  • wq保存更改和引號。

使用perl:

在這種情況下,我喜歡perl,因為

  1. 您無需擔心文件操作
  2. 您也可以輕松地備份文件。

命令:

$ perl -ni -e '/\b(boto3|botocore)\b/ || print;' requirements.txt

選項明細

  • -n遍歷文件中的行
  • -i在適當位置編輯文件。
  • -i.orig在適當位置編輯文件並使用擴展名'.orig'進行備份
  • -e執行perl命令

/ \\ 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.

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