有一些简单的脚本例子,功能是一样的。通过阅读这些例子,了解脚本语言的语法和语言特性。
熟悉命令行的使用技巧,选择语言需要知道能够用它来做什么。
hello world
PERL:
print "hello world\n"
GAWK:
BEGIN { print "hello world" }
一加一
PERL
$x= $x+1;
GAWK
x= x+1
打印变量
PERL
print $x, $y, $z;
GAWK
print x,y,z
Printing the first field in a file
PERL
while (<>) { split(/ /); print "@_[0]\n" }
GAWK
{ print $1 }
打印第一个字段
PERL
while (<>) { split(/ /); print "@_[0]\n" }
GAWK
{ print $1 }
按新排列字段持续,打印每行内容
PERL
while (<>) { split(/ /); print "@_[1] @_[0]\n" }
GAWK
{ print $2, $1 }
变量
PERL
command = "cat $fname1 $fname2 > $fname3"
GAWK
command = "cat " fname1 " " fname2 " > " fname3
循环
PERL:
for (1..10) { print $_,"\n" }
GAWK:
BEGIN { for (i=1; i<=10; i++) print i }
两个变量
PERL:
for (1..10) { print "$_ ",$_-1 } print "\n"
GAWK:
BEGIN { for (i=1; i<=10; i++) printf i " " i-1 print "" }
打印数组里面的值
PERL
foreach $x ( split(/ /,"this is not stored linearly") ) { print "$x\n" }
GAWK
BEGIN { split("this is not stored linearly",temp) for (i in temp) print temp[i] }
打印hash的key和值
PERL
$n = split(/ /,"this is not stored linearly"); for $i (0..$n-1) { print "$i @_[$i]\n" } print "\n"; for $i (@_) { print ++$j," ",$i,"\n" }
AWK
BEGIN { n = split("this is not stored linearly",temp) for (i=1; i<=n; i++) print i, temp[i] print "" for (i in temp) print i, temp[i] }
打印数据文件的所有行
PERL
open file,"/etc/passwd"; while () { print $_ }
GAWK
BEGIN { while (getline < "/etc/passwd") print }
打印一个字符串
PERL
$x = "this " . "that " . "\n"; print $x
GAWK
BEGIN { x = "this " "that " "\n" ; printf x }
构造打印数组
PERL
$assoc{"this"} = 4; $assoc{"that"} = 4; $assoc{"the other thing"} = 15; for $i (keys %assoc) { print "$i $assoc{$i}\n" }
GAWK
BEGIN { assoc["this"] = 4 assoc["that"] = 4 assoc["the other thing"] = 15 for (i in assoc) print i,assoc[i] }
数组排序
PERL
split(/ /,"this will be sorted once in an array"); foreach $i (sort @_) { print "$i\n" }
GAWK
BEGIN { split("this will be sorted once in an array",temp," ") for (i in temp) print temp[i] | "sort" while ("sort" | getline) print }
数组排序(#2) 推荐
GAWK
BEGIN { split("this will be sorted once in an array",temp," ") n=asort(temp) for (i=1;i<=n;i++) print temp[i] }
打印所有行,韵母替换为*
PERL
while () { s/[aeiou]/*/g; print $_ }
GAWK
{gsub(/[aeiou]/,"*"); print }
脚本文件
PERL
#!/pkg/gnu/bin/perl # this is a comment # open(stream1,"w | "); while ($line =) { ($user, $tty, $login, $junk) = split(/ +/, $line, 4); print "$user $login ",substr($line,49) }
GAWK
#!/pkg/gnu/bin/gawk -f # this is a comment # BEGIN { while ("w" | getline) { user = $1; tty = $2; login = $3 print user, login, substr($0,49) } }
Web应用
PERL
open(stream1,"lynx -dump 'cs.wustl.edu/~loui' | "); while ($line =) { if ($flag && $line =~ /[0-9]/) { print $line } if ($line =~ /References/) { $flag = 1 } }
GAWK
BEGIN { com = "lynx -dump 'cs.wustl.edu/~loui' &> /dev/stdout" while (com | getline line) { if (flag && line ~ /[0-9]/) { print line } if (line ~ /References/) { flag = 1 } } }