linux sed 總結

1.簡介

sed是一種行編輯器,它一次處理一行內容。

2.sed調用方式

sed [options] ‘command’ file(s)
sed [options] -f scriptfile file(s)

第一種直接在命令行中執行,第二種把命令寫到了腳本中,二者無本質區別。

  • 示例(1):打印hello.txt的內容
sed -n p hello.txt

說明:
-n:sed會在處理一行文本前,將待處理的文本打印出來,-n參數關閉了這個功能
p:命令表示打印當前行
hello.txt:待處理的文件
這個指令相當於cat

3.定址

告訴sed你期望處理的行,由逗號分隔的兩個數字表示,$符號表示最後一行;
當然也可以使用正則來定位期望處理的行。

  • 示例(2):打印hello.txt的第二行到最後一行
sed -n '2,$'p hello.txt
  • 示例(3):打印hello.txt中正則匹配"100"的行
sed -n '/100/'p hello.txt 

4.基本命令

hello.txt的內容爲

1 2 3
10 20 30
100 200 300
  • 命令:a
    在匹配行的後面加入一行文本

  • 示例(4)匹配100的行,後面加入一行"new line"

sed '/100/'a\ "new line" hello.txt

輸出內容爲:

1 2 3
10 20 30
100 200 300
new line
  • 命令:i
    在匹配行的前面加入一行文本

  • 示例(5)匹配100的行,前面加入一行"new line"

sed '/100/'i\ "new line" hello.txt

輸出內容爲:

1 2 3
10 20 30
new line
100 200 300
  • 命令:c
    將匹配行替換爲目的行

  • 示例(5)匹配100的行,替換爲"new line"

sed '/100/'c\ "new line" hello.txt

輸出內容爲:

1 2 3
10 20 30
new line
  • 命令:d
    將匹配行刪除

  • 示例(5)刪除匹配100的行

sed '/100/'d hello.txt

輸出內容爲:

1 2 3
10 20 30
  • 命令:s
    將匹配行替換
    詳細命令爲:s/pattern-to-find/replacement-pattern/g
    pattern-to-find:被替換的串
    replacement-pattern:替換成這個串
    g:全部替換,默認只替換匹配到的第一個
  • 示例(5)講100替換爲hello
sed 's/100/hello/g' hello.txt 

輸出內容爲:

1 2 3
10 20 30
hello 200 300

5.元字符集

^:匹配一行的開始
$:匹配一行的結束
.:匹配某個字符
[abc]:匹配指定範圍字符

6.實用命令

匹配以10開頭的行,並替換爲yes,並輸出

sed -n 's/^10/yes/p' hello.txt

輸出內容爲:

yes 20 30
yes0 200 300

取出文件中行手的行號與冒號
設hello.txt的內容爲

1:#!/bin/sh
2:cat hello.txt
3:exit

命令:

sed -n -e 's/^[0-9]\{1,\}://g'p hello.txt

輸出結果爲:

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