sed命令筆記備忘

# s命令會用斜線間指定的第二個文本字符串來替換第 一個文本字符串模式 
 echo "hello world" | sed 's/world/leyi/'  
# hello leyi

# 要在sed命令行上執行多個命令時,只要用-e選項就可以了 
 sed 's/hello/nihao/; s/world/leyi/' 1.txt 

#如果有大量要處理的sed命令,那麼將它們放進一個單獨的文件中通常會更方便一些。 可以在# sed命令中用-f選項來指定文件 
$ cat test.sed 
s/hello/nihao/
s/world/leyi/

sed -f test.sed 1.txt
nihao leyi
nihao leyi
nihao leyi
nihao leyi


a:追加  向匹配行後面插入內容 macOs下 需要在換行加反斜槓
# 行尾添加字符 
sed  “/$/a \\ 
big world" 1.txt

#  在帶有world的行後添加nihai leyi
sed "/world/a \\
nihao leyi" 1.txt


# 在第二行後添加nihai leyi
sed "2a \\
nihao leyi" 1.txt



c:更改  更改匹配行的內容
# 匹配帶world的行然後整行替換成big world
sed -i ''  "/world/c \\
big world" 1.txt


i:插入  向匹配行前插入內容 和-i 不同
# -i:直接對內容進行修改,不加-i時默認只是預覽,不會對文件做實際修改
# 在匹配的world行前插入big world
sed -i ''  "/world/i \\
big world" 1.txt

d:刪除  刪除匹配的內容
# 刪除帶world的行
sed -i ''  "/world/d " 1.txt

# 刪除空行
sed -i ''  "/^$/d " 1.txt

# 刪除1至2行
sed -i ''  "1,2d " 1.txt

# 刪除2至最後一行
sed -i ''  “2,$d " 1.txt


p :顯示,將某個選擇的數據打印顯示。通常 p 會與參數 sed -n 一起執行

# 顯示帶world的行等同 grep 'world' -r 1.txt
sed -n '/world/p' 1.txt 

# 顯示第一行等同 head -n 1 1.txt 
sed -n '1p' 1.txt 

# 顯示第最後一行等同 tail -n 1 1.txt 
sed -n '$p' 1.txt 

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章