簡體   English   中英

Bash sed用文件內容替換文本

[英]Bash sed replace text with file content

我想用file.txt內容替換字符串。

mtn="John"
fs=`cat file.txt`
lgtxt=`cat large_text.txt`

stxt1=`echo $lgtxt | sed "s/zzzz/$mtn/g"`
stxt2=`echo $stxt1 | sed "s/pppp/$fs/g"`

它將'zzzz'替換為'mnt'的值,但不是'pppp'。 文件file.txt包含名稱列表,例如:Tom jones Ted Baker Linda Evans在不同的行中。 我想將它們放在文件large_text.txt中的單獨行中,就像它們在oryginal文件中並用逗號分隔。

您不希望使用變量進行替換(例如,因為它可能包含換行符)。 我假設它是GNU sed,因為它是 在這種情況下,請查看GNU sed的r命令是否可以幫助您:

 `r FILENAME' As a GNU extension, this command accepts two addresses. Queue the contents of FILENAME to be read and inserted into the output stream at the end of the current cycle, or when the next input line is read. Note that if FILENAME cannot be read, it is treated as if it were an empty file, without any error indication. As a GNU `sed' extension, the special value `/dev/stdin' is supported for the file name, which reads the contents of the standard input. 

如果pppp在它自己的一行上,你可以使用類似的東西

/pppp/{
r file.txt
d
}

或者,使用e修飾符的s命令:

 `e' This command allows one to pipe input from a shell command into pattern space. If a substitution was made, the command that is found in pattern space is executed and pattern space is replaced with its output. A trailing newline is suppressed; results are undefined if the command to be executed contains a NUL character. This is a GNU `sed' extension. 

這看起來像

s/pppp/cat file.txt/e

如果pppp是中線,那就是你需要的。 此外,如果您需要在file.txt上進行進一步處理,您可以用您需要的任何內容替換cat (盡管您需要注意引用/\\ )。

最后一個選擇是考慮Perl,它將接受與shell命令非常相似的東西。

暫無
暫無

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

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