1. 程式人生 > >linux學習記錄-sed

linux學習記錄-sed

linux

文本處理工具

grep

sed(流編輯器)

awk(報告文本生成器)



sed基本用法

默認不編輯原文件,僅對模式空間中的數據處理。

sed:Stream EDitor


sed [options]‘AddressCommand‘ file ...

-n 靜默模式 不顯示模式空間中的內容

-i 修改原文件

-e script -e script:可以同時指定多個腳步

-f :指定一個腳本文件

-r:表示使用擴展正則表達式

Address

1.StartLine,EndLine

比如1,100

2./RegExp/

/^root/

3./pattern1/,/pattern2/

第一次被pattern1匹配到和行開始,至第一次被pattern2匹配到結束

4.LineNumber

指定的行

$表示最後一行

5.StartyLine,+N

從startline開始,向後的N行


Command:

d:刪除符合條件的行

sed ‘1,5d‘ /etc/fstab

sed ‘/oot/d‘ /etc/fstab

sed ‘1,+2d‘ /etc/fstab

sed ‘/^\//d‘ /etc/fstab 用^錨定行首的/ 需要加\轉義

p:顯示符合條件的行

a \string:在指定的行後面追加新行。內容為String

sed ‘/^\//a \#hello world\n#helo,linux‘ /etc/fstab

i \string:在指定的行前面追加新行。內容為String

r file:將指定的文件的內容添加至符合條件的行處

sed ‘2r /etc/issue‘ /etc/fstab

sed ‘$r /etc/issue‘ /etc/fstab 最後一行添加

w file :將指定範圍內的內容另存至指定的文件中

sed ‘/oot/w /tmp/oot.txt‘ /etc/fstab

s/pattern/string/修飾符:查找並替換 ,默認只替換每行中第一次被模式匹配到的字符串

加修飾符

g:表示全局替換

i:忽略字符大小寫

sed ‘s/^\//#/‘ /etc/fstab 行首的/替換為#

sed ‘s/\//#/g‘ /etc/fstab 全部/替換為#

sed ‘s@/@[email protected]

/* */ /etc/fstab [email protected]

$引用模式匹配到的字符串

history | sed ‘s#^[[:space:]]*##g‘ | cut -d‘ ‘ -f1

echo "/etc/rc.d" | sed -r ‘s@^(/.*/)[^/]+/?@\[email protected] 一個文件的父目錄


linux學習記錄-sed