sed使用(mac版)

1.增

#方式一,在第一行插入字符串helloworld0。vim里,注意1i\,后邊有一個空格
sed -i "" "1i\ 
> hellworld0
> " test.txt

#方式二,在第一行插入helloworld。注意 $'\n' 。
sed -i "" "1i\\"$'\n'"helloworld" test.txt
sed -i "" '1i\'$'\n''helloworld' test.txt

#在一行之后,追加字符串。(新增內容顯示在第二行)
sed -i "" "1a\\"$'\n'"helloworld" test.txt

2.刪

#直接刪除test.txt的第一行(d表示delete)
sed -i "" "1d" test.txt        

#直接刪除2-5行的內容       
sed -i "" "2,5d" test.txt

#直接刪除test.txt中world8所在行
sed -i "" "/world8/d” test.txt     

#直接刪除test.txt中正則匹配的字符串所在行
sed -i "" "/world.*/d” test.txt    

3.查

#打印第一行。p表示打印。
sed -n "1p" test.txt

#打印第一到三行。
sed -n "1,3p" test.txt

#打印包含 “beijing” 字符串所在的行。
sed -n "/beijing/p" test.txt

4.改

#把world1改成world0。s表示替換,2表示第二個world1,g表示全局。
sed -i "" "s/world1/world0/2" test.txt

#把第二行,第三行的所有hello替換為welcome
sed -i "" "2,3s/hello/welcome/" test.txt

#找到world3所在行,把所有的hello替換為welcome
sed -i "" "/world3/s/hello/welcome/g" test.txt

#正則匹配修改。把所有的 world+一個數(shù)字 改成了 beijing。
sed -i "" "s/world[0-9]/beijing/g" test.txt

#變量。\(.*\)會匹配出一個變量。\1表示第一個變量,\2表示第二個變量。
sed -i "" "s/\(.*\)-\(.*\)/\2-\1/g" test.txt

#把test.txt的2-5行替換為字符串
sed -i "" '2,5c\'$'\n''China' test.txt

5.讀取,寫入數(shù)據(jù)

#把test.txt的第一行替換為test1.txt的內容。
sed -i "" "1r test1.txt" test.txt

#把test1.txt的第三,四行數(shù)據(jù),寫入到test.txt。
sed -i "" "3,4w test.txt" test1.txt 
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容