2014-04-10 34 views
2

在給定行中插入文件的內容我想在當前文件夾和子文件夾中找到與模式匹配的所有文件(cs*.dat3),並從文件或bash中插入一段文本變成一個給定的行。它可能也是相匹配的文件,而不是一個給定的線的模式後,但我有使用sed

PRESSURE_RELIEF_PANELS 
EXIT PRESSURE_RELIEF_PANELS 

這樣的東西會放在兩次。幸運的是,第一個PRESSURE_RELIEF_PANELS總是在第32行,所以可以利用。我現在的看法是這樣的:

find . -name cs*.dat3 -exec sed '33iblah' {} \; 

其輸出

PRESSURE_RELIEF_PANELS 
blah 
EXIT PRESSURE_RELIEF_PANELS 

現在,而不是「嗒嗒」,我想插入文本塊。該文本存儲在一個文件中,因此可以暫時存儲在bash變量中,或者以某種方式將其作爲路徑或文件讀入sed。我一直無法找到一個好的解決方案,因爲我無法將sed的插入語句(i)與文件名語句(r)合併。

有人嗎?

回答

3

您可以使用帶有地址的讀取文件命令。他說:

sed '33rfile' input 

會插入後的input行數33名爲file文件。

您可能已經意識到r是GNU擴展。

從手動引用:

`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. 
+0

謝謝,這工作正常。爲了記錄我最後的工作命令是'find。 -name cs * .dat3 -exec sed -i'33r ../ text.dat'{} \;' –

1

你可以這樣做:

find . -name cs*.dat3 -exec sed -i.bak '/^PRESSURE_RELIEF_PANELS$/r file.dat' '{}' \; 

file.dat將數據插入。

+0

這給了我以下錯誤:'sed:-e表達式#1,字符1:未知命令:'^ 「'。什麼是'^'?第一場比賽還是什麼? –

+0

實際上,在複製/粘貼時,我錯過了'^'之前的'/'。 – anubhava

+0

是的,這是有道理的 - 這也適用。 '^'是否意味着只匹配第一次出現? –