iT邦幫忙

DAY 20
6

快快樂樂學會讓電腦幫我做事系列 第 17

[Shell Script] Day20-常用的指令介紹之快速搜尋取代文件內容

搜尋取代是一種很常見的文件編輯方式,但是如果有很多文件都需要『搜尋/取代』的話,那可就不是一件很輕鬆的工作! 所以就讓我們用一個指令讓電腦幫我們完成吧!
搜尋取代是一種很常見的文件編輯方式,但是如果有很多文件都需要『搜尋/取代』的話,那可就不是一件很輕鬆的工作!

所以今天要介紹的就是利用『下指令』來達到『搜尋/取代』的目的,只不過這一步就要很小心,如果一旦下錯指令那結果就真的會很嚴重,除非你有備份機制,例如修改程式碼時你有坐版本控制!

廢話不多說,就直接進入主題吧。搜尋取代的指令如下:

# -i 表示直接修改讀取檔案的內容,若沒有加-i則只會把修改過的內容顯示在畫面上而已。
sed –i ‘s/尋找目標字串/修改後的目標字串/g’ [輸入檔案名稱]

假設我們有一份文件如下:
Day20TestData.txt (內文資料取自 Wikipedia

Doraemon has a pocket from which he produces gadgets, medicines, and tools from the future. The pocket is called yōjigen-pocket (literally "fourth-dimensional pocket"). Some of the gadgets (dōgu) are based on real Japanese household devices with fanciful twists, but most are completely science fiction (although some may be based on folklore or religious stories). Thousands of dōgu have been featured in Doraemon." The number of gadgets has been approximated at 4,500. It is this constant variety which makes Doraemon popular both among children and among adults. In the series, the availability of dōgu sometimes depends on the money Doraemon has available, and he often says some dōgu are expensive in the future. The more famous ones include the "bamboo-copter" (which is very similar to the one that appears on the older series of Beany and Cecil), a small head accessory that allows flight; the "Anywhere Door," a door that opens up to any place the user wishes; and the "Time Machine." Some of the recurring dōgu also appear in Fujiko F. Fujio's other works, including 21-emon, Kaibutsu-kun, Kiteretsu Daihyakka, Mikio to Mikio, and Pāman.
[/code]

現在我們想把所有的 Doraemon 取代變成 小叮噹,我可以用以下指令完成:

sed -i 's/Doraemon/小叮噹/g' Day20TestData.txt

執行結果如下:
首先,先用 cat 確認一下目前檔案內容為何:

第二,執行 sed 命令來修改檔案:
sed -i 's/Doraemon/小叮噹/g' Day20TestData.txt

第三,確認是否已經修改:

成功!所有的 Doraemon 都已經被取代成 小叮噹了

sed 就這樣嗎?當然不是,他還是有許多的功能。不過光是尋找取代這一項,就真的很好用!明天在介紹 sed 其他的功能。

謝謝謝謝

鐵人賽文章分享
上一篇 常用的指令介紹之grep和awk
下一篇 常用的指令介紹之sed其他功能


上一篇
[Shell Script] Day19-常用的指令介紹之grep和awk
下一篇
[Shell Script] Day21-常用的指令介紹之sed其他功能
系列文
快快樂樂學會讓電腦幫我做事27
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

1
player
iT邦大師 1 級 ‧ 2013-10-11 18:47:20

sed 這個我滿少用的
我都用 管線符號 | 再接 grep
去搜尋

pajace2001 iT邦研究生 1 級 ‧ 2013-10-12 00:43:33 檢舉

對阿~用 grep 搜尋真的很好用
相較於 sed 我主要都是用來做 搜尋&取代 !
或者是列印關鍵字附近的資料使用

我要留言

立即登入留言