假設 source_library.txt 是源檔案,target_file.txt 是目標檔案,我使用 cat 命令在下面顯示檔案內容。
`$cat source_library.txt
// START method library function
{
common code starts...
I am the library which can be used in target files.
you can use me..
}
// END method library function
$ cat target_file.txt (before executing that sed command)
My name is Bikram
// START method library function
{
common code starts...
}
// END method library function
Outside of this method.`
執行以下命令后的輸出:
sed -i '/START method library function/,/END method library function/!b;//!d;/START method library function/r source_library.txt' target_file.txt
此命令的輸出:
`$cat target_file.txt (after executing that sed command)
My name is Bikram
// START method library function
// START method library function
{
common code starts...
I am the library which can be used in target files.
you can use me..
}
// END method library function
// END method library function
Outside of this method.`
但是我在 target_file.txt 中需要的預期輸出為
`My name is Bikram
// START method library function
{
common code starts...
I am the library which can be used in target files.
you can use me..
}
// END method library function
Outside of this method.
`
uj5u.com熱心網友回復:
使用 GNUsed
$ sed -e "/^common code starts/{e sed -n '/^common code starts/,/}/p' source_library.txt" -e 'd};/^$/,/}/d' target_file.txt
My name is Bikram
// START method library function
{
common code starts...
I am the library which can be used in target files.
you can use me..
}
// END method library function
Outside of this method.
uj5u.com熱心網友回復:
這個sed命令應該做的作業:
sed -n -i.backup '
/START method library function/,/END method library function/!p
/START method library function/r source_library.txt
' target_file.txt
uj5u.com熱心網友回復:
如果ed可用/可接受。
腳本script.ed,隨意命名。
/START method library function/;/END method library function/;?common code starts...?;/}/-w tmp.txt
E target_file.txt
/{/;/common code/;/}/;?{?r tmp.txt
;/^$/d
,p
Q
現在運行
ed -s source_library.txt < script.ed
使用here document, 類似的東西。
#!/bin/sh
ed -s source_library.txt <<-'EOF'
/START method library function/;/END method library function/;?common code starts...?;/}/-w tmp.txt
E target_file.txt
/{/;/common code/;/}/;?{?r tmp.txt
;/}/-d
,p
Q
EOF
它創建一個臨時檔案(名為 的檔案
tmp.txt),內容來自source_library.txt如果之后不需要臨時檔案,請
!rm tmp.txt在該行之后添加。;/}/-d如果不需要
,p輸出,則洗掉。stdout更改
Q為w是否需要對 target_file.txt進行就地編輯。
uj5u.com熱心網友回復:
cat source_library.txt | sed '/START method library function/,/END method library function/{d;r /dev/stdin}' target_file.txt
正如我們在這個問題中討論的那樣,您可以使用r /dev/stdin來確保r在替換部分的第一行之后讀取的是空流。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/514449.html
標籤:linux重击壳sed
