尋找並替換

尋找並替換

我有一個包含關鍵字的檔案RESOURCE。它可以出現在文件中的任何位置,例如:

[email protected]

現在我想替換[email protected][email protected].我必須搜尋可以找到關鍵字的行RESOURCE,然後替換等號後面的單字。關鍵字RESOURCE必須保持不變。

有人可以幫我解決這個問題嗎?

輸入:

[email protected]

輸出:

[email protected]

答案1

grep在這種情況下沒有用,因為它不允許您修改文件的內容。

相反,人們可以sed像這樣使用:

fromaddr='[email protected]'
toaddr='[email protected]'

sed '/^RESOURCE=/s/='"$fromaddr"'$/='"$toaddr"'/' file >newfile

給出file

some data
[email protected]
[email protected]
[email protected]
[email protected]
more data

這創建newfile

some data
[email protected]
[email protected]
[email protected]
[email protected]
more data

sed表達式將選擇以字串 開頭的行RESOURCE。對於每個這樣的行,它將替換電子郵件地址(如果該行中存在)。用於替換的模式確保我們匹配=並且地址在行尾結束。

答案2

命令sed比較好。

sed -i 's/[email protected]/[email protected]/' yourfile

上面的方法在我的測試中有效,但如果你想自己測試一下,那麼你可以先嘗試這個:

sed 's/[email protected]/[email protected]/' yourfile

這會將更改寫入標準輸出而不影響檔案。

無論哪種方式,它都會提供您想要的更改:

[email protected]

RESOURCE如果文件中的值不同且您想要將其變更為不同的內容,則:

grep RESOURCE= yourfile

這將返回該行所在位置並顯示該值。

然後你可以使用

sed 's/[email protected]/[email protected]/' yourfile

為了供將來參考,重要的是在您最初的問題中明確所有這些內容,以便您可以獲得所需的幫助,而無需所有這些繁瑣的內容。

答案3

您似乎是在說您想要替換出現在=, 不管它是什麼例如,在範例資料中,您想要替換[email protected].但你是說,無論後面的字串=是什麼,你都想用它來替換它[email protected]——顯然你想要硬編碼。

關於如何執行此操作有一些變化。最簡單的是

sed 's/RESOURCE=.*/[email protected]/'

它(像下面所有的命令一樣)使用了.*“匹配任何存在的東西”這一事實。如果您不想輸入RESOURCE=兩次,可以將上面的內容縮短為

sed 's/\(RESOURCE=\).*/\[email protected]/'

其中\(\)將搜尋字串的一部分標記為一個群組(最多可以有九個群組),並且\1表示替換為第一組。

上述命令將會尋找並取代RESOURCE= 該行中出現的任何位置。因此,例如,輸入

# Lakshminarayana wants to change all occurrences of "RESOURCE=".
[email protected]
[email protected]
[email protected]
FOX RESOURCE=The quick brown fox
# Comment: Originally line 2 said [email protected]

將改為

# Lakshminarayana wants to change all occurrences of "[email protected]
[email protected]
[email protected]
[email protected]
FOX [email protected]
# Comment: Originally line 2 said [email protected]

如果您只想匹配RESOURCE=出現在行首的時間,請使用^

sed 's/^RESOURCE=.*/[email protected]/'

或者

sed 's/^\(RESOURCE=\).*/\[email protected]/'

如果您只想替換資源值,而不是該行的整個其餘部分 - 例如,

[email protected]    [email protected]

[email protected]   [email protected]

這也是可以做到的。編輯您的問題,準確說出您想要的內容,並提供完整、清晰的解釋例子。


好的,選擇以上一項s命令。現在,如果您想就地編輯文件(如您所示),請執行以下操作

sed  -i  {s command }  { yourfile }

如果你想產生一個新文件,請執行

sed  {s command }  { oldfile }  >  { newfile }

實際上不要輸入{};他們在那裡只是為了劃界。

相關內容