Linux:高度なシェルスクリプト(sed / gawk)

目次

高度なSedコマンド

ホールドスペースとパターンスペース

Sedの高度な記事のサンプルアプリケーション

高度なgawkコマンド


 

#この記事は研究ノートです

 

高度なSedコマンド

1> nコマンド:次の行に移動します

小文字のnコマンドは、処理のためにデータストリームの次の行に移動するようにsedエディターに指示します。

 

1.1nコマンドの原理

nコマンドは、モデルスペースの前の行をカバーする次の行を事前に読み取るだけです(削除されないため、標準出力に出力されます)。コマンドが正常に実行されない場合(スキップしない:フロントエンドの条件が一致しない)、あきらめます。任意のコマンドを実行し、新しく読み取ったコンテンツに対してsedを再実行します。

例:

aaaファイルから偶数行を取り出します

1

2

3

4

5

6

7

8

9

10

cat aaa 

This is 1    

This is 2    

This is 3    

This is 4    

This is 5    

     

sed -n 'n;p' aaa         //-n表示隐藏默认输出内容    

This is 2    

This is 4


注:読み取りこれは1、nコマンドを実行、モードスペースはこれ2、実行p、モードスペースの内容を出力これは2、次に読み取りこれは3、nコマンドを実行、モードスペースはこれです4. pを実行し、モードスペースの内容を出力します。これは4です。次に、これは5です。これ以上ないので、nコマンドを実行します。終了し、pコマンドをあきらめます。

したがって、最後に偶数行が出力されます。

 

2> Nコマンド:テキスト行をマージします

大文字のNは、パターンスペース内の既存のテキストに次のテキスト行を追加します。これにより、2つのテキスト行が同じパターンスペースにマージされ、テキスト行は改行で区切られます。ファイル内の2行に散らばっている可能性のあるテキストを検索する場合、これは非常に便利な機能です。

 

2.1 Nコマンドの原理:

Nコマンドは、単に次の行をパターンスペースに追加し、同時に2行を1行として扱いますが、2行の間に\ n新しい行文字が残っています。コマンドが正常に実行されない場合(スキップしない:フロントエンドの条件が一致しない)、その後、コマンドをすべて放棄し、新しく読み取ったコンテンツに対してsedを再実行します。

例:

aaaファイルから奇数行を読み取る

1

2

3

4

5

6

7

8

9

10

11

cat aaa   

This is 1   

This is 2   

This is 3   

This is 4   

This is 5   

                                                     

sed -n '$!N;P' aaa            

This is 1   

This is 3   

This is 5

コメントでは、1はこれが1であることを表し、2はこれが2であることを表します。

注:読み取り1、$!条件が満たされている(最後の行ではない)、Nコマンドを実行、1 \ n2を取得、Pを実行、印刷1、読み取り3、$!条件が満たされている(最後の行ではない)、Nコマンドを実行、取得3から\ n4、Pを実行、3を印刷、5を読み取る、$!条件が満たされない、Nをスキップ、Pを実行、5を印刷

2.2構成例

例1
$ cat data2.txt
this is the header line.
this is the first data line.
this is the second data line.
this is the last line.

$ sed '/first/{N;s/\n/ /}' data2.txt
this is the header line.
this is the first data line. this is the second data line.
this is the last line.

例2
$ cat data3.txt
on Tuesday,the linux system
administrator's group meeting will be held.
all system administrators should attend.
thank you for your attendance.

$ sed 'N;s/system.administrator/desktop user/' data3.txt
on Tuesday,the linux desktop user's group meeting will be held.
all desktop users should attend.
thank you for your attendance.

 

3>前の行のコマンドDコマンドのみを削除します

一致する行が複数ある場合、Dコマンドはパターンスペースの最初の行のみを削除します

 

3.1Dコマンドの動作原理

Dコマンドは、現在のモードスペースの先頭から\ n(標準出力に送信されない)までコンテンツを削除し、後続のコマンドを破棄しますが、残りのモードスペースでsedを再実行します。

Dコマンドの例

aaaファイルから最後の行を読み取ります

1

2

3

4

5

6

7

8

9

cat aaa   

This is 1   

This is 2   

This is 3   

This is 4   

This is 5   

                                                

sed 'N;D' aaa           

This is 5

注:読み取り1、実行N、取得1 \ n2、実行D、取得2、実行N、取得2 \ n3、実行D、取得3など、取得5、実行N、条件-nパラメータがないため、終了できません。出力5

 

3.2構成例


$ cat data5.txt

this is the header line.
this is a data line.

this is the last line.

例1:
$ sed '/^$/{N;/header/D}' data5.txt
this is the header line.
this is a data line.

this is the last line.

例2:打印最后两行
sed '$!N;$!D' data5.txt

this is the last line.

 

4>前の行のみを印刷するPコマンド

一致する行が複数ある場合、Pコマンドはパターンスペースの最初の行のみを出力します

$ sed -n 'N;/system\nadministrator/P' data3.txt
on Tuesday,the linux system

5>除外コマンド(!)

例1
$ cat data2.txt
this is the header line.
this is the first data line.
this is the second data line.
this is the last line.

$ sed -n '/headeer/!p' data2.txt
this is the first data line.
this is the second data line.
this is the last line.

6>ブランチ。データフローを変更するために使用されます

形式:[アドレス] b [:ラベル]

addressパラメーターは、ブランチコマンドをトリガーするデータの行を決定し、labelパラメーターはジャンプ先の場所を定義します。

例1
$ cat data2.txt
this is the header line.
this is the first data line.
this is the second data line.
this is the last line.
$ sed '{2,3b;s/this is /is this/;s/line./test?/}' data2.txt
is this the header test?
this is the first data line.
this is the second data line.
is this the last test?

例2
$ sed '{/first/b jump1;s/this is the/no jump on/
>:jump1
>s/this is the/jump here on/}' data2.txt

no jump on header line
jump here on first data line
no jump on second data line
no jump on last line

例3
$ sed -n '{
> :start
> s/,//1p
> b start
> }'

 

7>テスト(テスト)コマンド。sedエディタースクリプトの実行フローを変更するために使用されます。これは、論理演算子の「または」に相当します。

例1
$ cat data2.txt
this is the header line.
this is the first data line.
this is the second data line.
this is the last line.
$ sed '{
>s/first/matched/
>t
>s/this is the/no match on/
}' data2.txt
no match on header line
this is the matched data line
no match on second data line
no match on last line

例2
$ echo "this,is,a,test,to,remove,commas."|sed -n '{
>:start
>s/,/ /1p
>b start
}'
#当无需替换时,测试命令不会跳转而是继续执行剩下的脚本

 

8>代替モード/後方参照(&)

&記号は、replaceコマンドで一致するパターンを表すために使用されます。文字列の一部を照合する場合は、括弧を使用してパターン内のサブパターンを定義し、\ 1、\ 2などを使用して呼び出し元のサブパターンを表すことができます。

例1
$ echo 'the cat sleeps in his hat'|sed 's/.at/"&"/g'
the "cat" sleeps in his "hat"

例2
$ echo 'the system administrator manual'|sed '
>s/\(system\) administrator/\1 user/'
the system user manual

例3
$ echo '1234567'|sed '{
>:start
>s/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/
>t start
>}'
1,234,567

 

ホールドスペースとパターンスペース

モードスペース:sedエディターが処理するテキストを格納するバッファー領域です。Sedは、一度に1行のテキストを読み取り、それをパターンスペースに配置して、編集コマンドを実行します。

スペースを確保する:一部の行を一時的に保存するためのバッファー。

保持スペースを操作するための5つのコマンドがあります。

h パターンスペースをホールドスペースにコピーします(上書きされます)
H スペースを保持するためにパターンスペースを追加します
g ホールドスペースをパターンスペースにコピーします
G パターンスペースに保持スペースを追加します
バツ パターンスペースの内容を交換し、スペースを保持します

 

例1
$ cat data2.txt
this is the header line.
this is the first data line.
this is the second data line.
this is the last line.
$ sed -n '{1!G;h;$p}' data2.txt
this is the last line.
this is the second data line.
this is the first data line.
this is the header line.

 

 

Sedの高度な記事のサンプルアプリケーション

サンプルテキスト:

catdata2.txt
  これはヘッダー行です。
  これが最初のデータ行です。
  これは2番目のデータ行です。
  これが最後の行です。


实例:
例1:加倍行间距,每行后面加一行空白行;
$ sed 'G' data2.txt
this is the header line.

this is the first data line.

this is the second data line.

this is the last line.

$ sed '$!G' data2.txt      #每行后面加一空白行,最后一行不加
this is the header line.

this is the first data line.

this is the second data line.

this is the last line.
$

 

例2:给文件中的行编号;
$ sed '=' data2.txt | sed 'N;s/\n'/ /'
1 this is the header line.
2 this is the first data line.
3 this is the second data line.
4 this is the last line.
#如果有空白行的话,需要注意先去除空白行
例3:打印末尾10行
$ sed '{
> :start
> $q;N;11,$D
> b start
> }' data7.txt
例4:删除空白行
$ sed '/./,/^$/!d' data8.txt     #删除连续空白行;
$ sed '/./,$!d' data9.txt        #删除开头n行空白行;
$ sed '{                         #删除末尾空白行;
> :start
> /^\n*$/{$d;N;b start}
> }'

 

高度なgawkコマンド

1>組み込み変数

FIELDWIDTHS 各データフィールドの正確な幅を定義するスペースで区切られた一連の番号
FS 输入字段分隔符,默认是空格符
RS 输入记录分隔符,每行是一条记录,默认是换行符
OFS 输出字段分隔符,默认是空格符
ORS 输出记录分隔符,每行是一条记录,默认是换行符

 

数据变量:

NF 字段总数
NR 已处理的行数
ENVIRON

关联数组组成的shell环境变量值,格式如下

print ENVIRON["HOME"]

   
例1:将逗号分隔符替换为“-”,并输出前三项
$ cat data1
data11,data12,data13,data14,data15
data21,data22,data23,data24,data25
data31,data32,data33,data34,data35

$ gawk 'BEGIN{FS=",";OFS="-"} {print $1,$2,$3}' data1
data11-data12-data13
data21-data22-data23
data31-data32-data33

 

例2:将每行当作一个字段,把空白行当作记录分隔符
$ cat data2
riley mullen
123 main street
chicago,il 60601
555-1234

frank williams
456 oak street
indianapolis ,in 46201
5559876

haley snell
4231 elm street
detroit,mi 48201
555-4938

$ gawk 'BEGIN{FS="\n";RS=""} {print $1,$4}' data2
riley mullen 555-1234
frank williams 555-9876
haley snell 555-4938
例3:按固定宽度分隔字段
$ cat data1b
1005.3247596.37
115-2.349194.00
05810.1298100.1

$ gawk 'BEGIN{FIELDWIDTHS="3 5 2 5"}{print $1,$2,$3,$4}' data1b
100 5.324 75 96.37
115 -2.34 91 94.00
058 10.12 98 100.1
例4:在脚本中使用变量赋值
$ gawk '
> BEGIN{
> testing="this is a test"
> print testing
> testing=46
> print testing
> }'

$ this a testing
$ 45
遍历关联数组
$ gawk 'BEGIN{
> var[a]=1
> var[g]=2
> var[u]=3
> for (test in var)
> {
> print "index:",test," "- Value:",var[test]
> }
> }'

index: u  - Value: 3
index: a  - Value: 1
index: g  - Value: 2

删除数组元素值:
delete array[index]
匹配限定
$ gawk -F: '$1 ~ /rich/{print $1,$NF}' data1
rich /bin/bash
#这个例子会在第一个数据字段中查找文本rich。如果在记录中找到了这个模式,它会打印
该记录的第一个和最后一个数据字段值;
数学表达式应用
$ gawk -F: '$4 == 0 {print $1}' /etc/passwd
root
sync
shutdown
halt
operator
结构化命令,if语句
if (condition)
statement1
也可以将它放在一行上,像这样:
if (condition) statement1

$ gawk '{if ($1 > 20) print $1}' data4
$ gawk '{
> if ($1 > 20)
> {
> x=$1 * 2
> print x
> }
> }' data4


$ gawk '{
> if ($1 > 20)
> {
> x = $1 * 2
> print x
> } else
> {
> x = $1 / 2
> print x
> }}' data4

可以在单行上使用else子句,但必须在if语句部分之后使用分号。
if (condition) statement1; else statement2


结构化命令,while语句
while (condition)
{
statements
}

$ gawk '{
> total = 0
> i = 1
> while (i < 4)
> {
> total += $i
> i++
> }
> avg = total / 3
> print "Average:",avg
> }' data5


$ gawk '{
> total = 0
> i = 1
> while (i < 4)
> {
> total += $i
> if (i == 2)
> break
> i++
> }
> avg = total / 2
> print "The average of the first two data elements is:",avg
> }' data5

结构化命令,do-while语句类似于while语句,但会在检查条件语句之前执行命令。下面是do-while语
句的格式。
do
{
statements
} while (condition)
这种格式保证了语句会在条件被求值之前至少执行一次。当需要在求值条件前执行语句时,
这个特性非常方便。
$ gawk '{
> total = 0
> i = 1
> do
> {
> total += $i
> i++
> } while (total < 150)
> print total }' data5



for语句是许多编程语言执行循环的常见方法。gawk编程语言支持C风格的for循环。
for( variable assignment; condition; iteration process)
将多个功能合并到一个语句有助于简化循环。
$ gawk '{
> total = 0
> for (i = 1; i < 4; i++)
> {
> total += $i
> }
> avg = total / 3
> print "Average:",avg
> }' data5
格式化输出,printf,和c语言用法一样
c 将一个数作为ASCII字符显示
d 显示一个整数值
i 显示一个整数值(跟d一样)
e 用科学计数法显示一个数
f 显示一个浮点值
g 用科学计数法或浮点数显示(选择较短的格式)
o 显示一个八进制值
s 显示一个文本字符串
x 显示一个十六进制值
X 显示一个十六进制值,但用大写字母A~F


注意,你需要在printf命令的末尾手动添加换行符来生成新行。没添加的话,printf命令
会继续在同一行打印后续输出。

printf默认输出是右对齐,可通过“-”来控制成左对齐:
$ gawk 'BEGIN{FS="\n"; RS=""} {printf "%-16s %s\n", $1, $4}' data2
Riley Mullen (312)555-1234
Frank Williams (317)555-9876
Haley Snell (313)555-4938
$

处理浮点数:
$ gawk '{
> total = 0
> for (i = 1; i < 4; i++)
> {
> total += $i
> }
> avg = total / 3
> printf "Average: %5.1f\n",avg
> }' data5
Average: 128.3
Average: 137.7
Average: 176.7
$
#打印test.txt的第3行至第5行
awk 'NR==3,NR==5 {print}' test.txt
#打印test.txt的第3行至第5行的第一列与最后一列
awk 'NR==3,NR==5 {print $1,$NF}' test.txt

#打印test.txt中长度大于80的行号
awk 'length($0)>80 {print NR}' test.txt

#计算test.txt中第一列的总和
cat test.txt|awk '{sum+=$1}END{print sum}'

#添加自定义字符
ifconfig eth0|grep 'Bcast'|awk '{print "ip_" $2}'


#格式化输出
awk -F: '{printf "% -12s % -6s % -8s\n",$1,$2,$NF}' /etc/passwd

 

注:本章内容为读书笔记,摘自《Linux命令行与shell脚本编程大全》第3版。

おすすめ

転載: blog.csdn.net/qq_35229961/article/details/90693541