簡體   English   中英

bash:如何用部分內容替換文本文件中的整行

[英]bash: How to replace an entire line in a text file by a part of its content

我在 Documentos 文件夾中有一個名為 texto.txt 的文本文件,其中包含一些如下所示的值:

cat ~/Documentos/texto.txt

65f8: Testado
a4a1: Testado 2

所以我想通過使用自定義函數來更改整行,該函數獲取新值作為參數。 新值將始終保留前 6 個字符,僅更改它們之后的字符。 雖然我只測試前四個。

然后我編輯了我的 .bashrc,包括我的函數,如下所示。

muda() 
{ 
export BUSCA="$(echo $* | cut -c 1-4)";
sed -i "/^$BUSCA/s/.*/$*/" ~/Documentos/texto.txt ;}

當我運行下面的命令時,它就像一個魅力,但我覺得它可以改進。

muda a4a1: Testado 3

結果:

cat ~/Documentos/texto.txt

65f8: Testado
a4a1: Testado 3

有沒有更聰明的方法來做到這一點? 也許通過擺脫 BUSCA 變量?

我會寫:

muda() {
    local new_line="$*"
    local key=${newline:0:4}
    sed -i "s/^${key//\//\\/}.*/${new_line//\//\\/}/" ~/Documentos/texto.txt
}

筆記:

  • 使用local變量,而不是導出的環境變量
  • 不調用剪切,bash 可以提取一個子串
  • 轉義變量值中的任何斜杠,以便 sed 代碼不會被破壞。

暫無
暫無

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

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