簡體   English   中英

如何通過終端查找和替換文本文檔中的行

[英]How do you find and replace a line in a text document through terminal

我有一個用vim創建的shell腳本。 唯一的想法我知道它是一個var名稱。

在文檔的某處有一行:

SecondHome='/Users/me/Documents/code/'

這個值是不正確的,但是通過執行新功能的shell腳本而不改變shell腳本的功能。

我想做的事情如下:

grep -n "SecondHome" somefile.sh

這會吐出行號+匹配,但只改變第一個,因為那是變量定義。

我當時想要在那條線上做一個替換,以使它看起來像:

export SecondHome=$DirPath/code/$Repo

然后運行已修改的腳本文件。

#!/bin/zsh
export DirPath=/Users/me/Documents/
export Repo=MyNewRepo/
export LineNumber=$(grep -n "SecondHome" somefile.sh)
#carry out replace on somefile.sh at $LineNumber with: export SecondHome=$DirPath/code/$Repo/
. ./somefile.sh

這可能嗎?

sed -i.bak '/SecondHome=/s,=.*,=$DirPath/code/$Repo,' somefile.sh

sed -i.bak expression file進行expression上的文件,修改它-i N將。

表達式位於表單/regex/command ,該command在與regex匹配的行上運行command

commands,search,replace, ,用於搜索和替換文本。

換句話說,它通過查找包含SecondHome=行來修改文件,並用等號替換等號之后的所有內容。

如果在替換腳本中定義$ DirPath / $ Repo而不在somefile.sh中,則還可以用雙引號替換單引號

暫無
暫無

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

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