Linux之sed命令(包含MacOS的用法)
一、概述
Linux下的sed命令是一種流編輯器,用于在命令行中對文本進行處理,常見的操作如:添加、修改、刪除、追加等。
當所用系統(tǒng)為MacOS時,直接使用sed會出現(xiàn)
command a expects \ followed by text
此類報錯,處理方法如下:
解決方案1:sed命令改寫 --> 添加一個空串
sed -i ‘s/apple/applewatch/g' /tmp/a.txt
- 改寫為
sed -i ‘' ‘s/apple/applewatch/g' /tmp/a.txt
解決方案2:調(diào)整mac下的sed命令 --> 安裝gnu-sed
- 執(zhí)行:
brew install gnu-sed alias sed=gsed
本人建議使用第二種方式解決,一勞永逸。
extra:在使用sed新增一行時會使用到\,macOS會把反斜杠解析為命令結束字符,后面不允許攜帶新字符,導致報錯
extra characters after \ at the end of a command
只能通過把命令分割成兩行內(nèi)容。
示例:
原命令:sed -i '$a new line' /tmp/a.txt macOS下需要寫成: sed -i '' -e '$a\ new line' /tmp/a.txt
二、用法
以下介紹sed命令常用方法。
1、文件末尾追加一行
sed -i '$a <new_line>' <file_name> 示例:sed -i '$a this is a new line' /tmp/sed.txt
2、指定行后新增一行
sed -i '/<specific_line>/a\<new_line>' <file_name> 示例:sed -i '/an existing line/a\this is a new next line' /tmp/sed.txt
其中<specific_line>可以為模糊匹配,例如為line但有多行都包含line,此時會在所有包含line關鍵字的行后都新增一行。
此規(guī)則以下都適用。
3、指定行前新增一行
sed -i '/<specific_line>/i\<new_line>' <file_name> 示例:sed -i '/an existing line/i\this is a new upper line' /tmp/sed.txt
4、修改指定行
sed -i 's/<old_content>/<new_content>/g' <file_name> 示例:sed -i 's/magic_switch=0/magic_switch=1/g' /tmp/sed.txt
5、刪除指定行
sed -i '/<specific_line>/d' <file_name> 示例:sed -i '/trash_line/d' /tmp/sed.txt
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
在CentOS VPS上通過SSH安裝 MySQL的方法圖解
這篇文章主要介紹了在CentOS VPS上通過SSH安裝 MySQL,需要的朋友可以參考下2018-12-12
bt寶塔面板php7.3、php7.4不支持ZipArchive解決方法
這篇文章主要介紹了bt寶塔面板php7.3、php7.4不支持ZipArchive解決方法,需要的朋友可以參考下2020-06-06
基于SecureCRT向遠程Linux主機上傳下載文件步驟圖解
這篇文章主要介紹了基于SecureCRT向遠程Linux主機上傳下載文件,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-06-06
Linux多線程環(huán)境下 關于進程線程終止函數(shù)總結
下面小編就為大家?guī)硪黄狶inux多線程環(huán)境下 關于進程線程終止函數(shù)總結。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01

