サーチ…


前書き

Sedコマンドは、 アドレスまたはアドレス範囲を使用して特定の行にのみ動作するように指定することができます。

特定線

$ cat ip.txt
address
range
substitution
pattern
sample
  • N番目のライン

    $ sed -n '2p' ip.txt 
    range
    
    $ sed '3d' ip.txt 
    address
    range
    pattern
    sample
    
  • 最後の行

    $ sed -n '$p' ip.txt 
    sample
    

特定のラインの範囲

$ cat ip.txt 
address
range
substitution
pattern
sample
  • 指定された範囲は、これらの行番号を含みます

    $ sed -n '2,4p' ip.txt 
    range
    substitution
    pattern
    
  • $を使用して最後の行を指定できます。分かりやすくするために、アドレスとコマンドの間にスペースを使用できます

    $ sed -n '3,$ s/[aeiou]//gp' ip.txt 
    sbstttn
    pttrn
    smpl
    

GNU sed
  • i番目のラインからi + j番目のラインまで

    $ sed '2,+2d' ip.txt 
    address
    sample
    
  • i番目のラインとi + ji + 2 ji + 3 番目の jなど

    $ sed -n '1~2p' ip.txt 
    address
    substitution
    sample
    

正規表現パターンに一致する行

$ cat ip.txt 
address
range
substitution
pattern
sample
Add Sub Mul Div
  • パターンに一致する線

    $ sed '/add/d' ip.txt 
    range
    substitution
    pattern
    sample
    Add Sub Mul Div
    
    $ sed -n '/t/p' ip.txt 
    substitution
    pattern
    
    $ sed -n '/[A-Z]/ s| |/|gp' ip.txt 
    Add/Sub/Mul/Div
    
  • パターンの範囲

    $ sed -n '/add/,/sub/p' ip.txt 
    address
    range
    substitution
    
    $ sed -n '/a/,/e/p' ip.txt 
    address
    range
    pattern
    sample
    

注意

  • 2番目の例では、それは2つの範囲 - 行1,2および4,5
  • パターンの指定に/代わりに他の文字を使用する方法については、 異なる区切り文字の使用を参照してください

GNU sed
  • 大文字と小文字を区別しない一致

    $ sed -n '/add/Ip' ip.txt 
    address
    Add Sub Mul Div
    
    $ sed -n '/add/I,/sub/p' ip.txt 
    address
    range
    substitution
    Add Sub Mul Div
    

数値とパターンの両方を使用して範囲を指定する

$ cat ip.txt 
address
range
substitution
pattern
sample
Add Sub Mul Div
  • 行番号と行の一致パターン

    $ sed -n '2,/pat/p' ip.txt 
    range
    substitution
    pattern
    
  • 行一致パターンと行番号

    $ sed '/pat/,$d' ip.txt 
    address
    range
    substitution
    

GNU sed
  • ラインマッチングパターン+それに続くライン数

    $ sed -n '/add/I,+1p' ip.txt 
    address
    range
    Add Sub Mul Div
    
  • パターンが入力の最初の行に一致すると、 0が開始行番号として使用され、範囲の終了を通知することができます

    $ sed -n '0,/r/p' ip.txt 
    address
    
    $ sed -n '1,/r/p' ip.txt 
    address
    range
    
    $ sed -n '0,/u/p' ip.txt 
    address
    range
    substitution
    

アドレス範囲の否定

$ cat ip.txt 
address
range
substitution
1234
search pattern
sample
Add Sub Mul Div
  • 指定されたアドレス以外の行の削除

    $ sed '/[0-9]/!d' ip.txt 
    1234
     
    $ sed -n '/[0-9]/p' ip.txt 
    1234
      
    $ sed '$!d' ip.txt 
    Add Sub Mul Div
      
    $ sed -n '$p' ip.txt 
    Add Sub Mul Div
    
  • パターンに合致しない行を検索して置換する

    $ sed '/ /! s/^/#/' ip.txt 
    #address
    #range
    #substitution
    #1234
    search pattern
    #sample
    Add Sub Mul Div
    
    $ sed '/add/,/sub/! s/[aeiou]//gi' ip.txt 
    address
    range
    substitution
    1234
    srch pttrn
    smpl
    dd Sb Ml Dv
    


Modified text is an extract of the original Stack Overflow Documentation
ライセンスを受けた CC BY-SA 3.0
所属していない Stack Overflow