2011-03-12 44 views
1

如何根據來自其他文件的值替換文件中的字符串。如何基於來自另一個文件的值替換文件中的字符串? (內部示例)

實施例,2檔 - 輸入,輸出

輸入:

12345 1 

輸出:

(1,'a lot of text', 'some other info',0,null, 12345), 
(2,'a lot of text', 'some other info',0,null, 12345), 
(3,'a lot of text', 'some other info',0,null, 12345), 
(4,'a lot of text', 'some other info',0,null, 12345), 
(5,'a lot of text', 'some other info',0,null, 12345); 

需要做:從文件 '輸入'

讀取值,並在文件'輸出'中將'12345'全部替換爲'1'。 感謝您的幫助提前

回答

4

如何:

sed `sed 's|\(.*\) \(.*\)|s/\1/\2/|' input` output 
+0

+1簡單易用 – GingerHead 2012-03-13 14:24:05

0
cat input | while read src rep 
do 
    sed -i "s, $src), $rep),g" output 
done 

記得做一個「輸出」的備份。

編輯:另請注意,如果「輸入」包含的字符是特殊 sed,這將失敗。對於簡單的字母/數字,它會正常工作。

+0

另請考慮'perl -pe'作爲通用目的,功能更強大的'sed'。 – Ben 2011-03-12 16:31:51

+0

謝謝,我找到了像你所建議的解決方案,但我不能使用它,因爲錯誤:bash:語法錯誤附近的意外令牌'完成' – 2011-03-12 16:35:50

+0

感謝您指向sed的指針! – 2011-03-12 17:03:21

0

好吧,我遇到了這個解決方案:

cat input | awk '{ cmd = "sed s/," $1 ",/," $2 ",/g" " output > output.new"; print system(cmd) }' 
+0

不需要'貓';只需將該文件提供給'awk'。 – 2011-03-14 03:56:17

2

不需要有AWK反覆調用sed。只需讓AWK將第一個文件讀入數組中:

awk -F "[)]" 'NR == FNR {a[$1] = $2; next} {sub($(NF-1), a[$(NF-1)]); print}' key-value-file main-file 
+0

頭腦風暴+1! – GingerHead 2012-03-13 14:23:22

相關問題