Scripts

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Scripts as PDF for free.

More details

  • Words: 7,980
  • Pages: 67
Scripts

/)

Cyril Huang [email protected]

uŒÌã

June 14, 2002

Contents 1 2

GŽ $Bourne shell 2.1 + . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.1.1 shellÎ#‚ . . . . . . . . . . . . . . . . . . . . . . . . . . 2.1.2 ƕshell scriptsubshell . . . . . . . . . . . . . . . . . . 2.2 ŽóÐóÿà;¶® . . . . . . . . . . . . . . . . . . . . . . . . 2.2.1 Žó¸à . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.2.2 Srquote . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.2.3 Àrݎó゠. . . . . . . . . . . . . . . . . . . . . . 2.2.4 •(Žó . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.2.5 ×°/Žó . . . . . . . . . . . . . . . . . . . . . . . . . 2.3 Ðó9jÿà; . . . . . . . . . . . . . . . . . . . . . . . . . . 2.3.1 ÿà;P . . . . . . . . . . . . . . . . . . . . . . . . . . 2.4 ¥Š²I/˜úƒ . . . . . . . . . . . . . . . . . . . . . . . . . 2.4.1 /˜úƒ . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.4.2 ²Iúƒ . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.4.3 Žó. . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.5 File descriptorI/O0' . . . . . . . . . . . . . . . . . . . . . . . 2.6 ø×?Žf . . . . . . . . . . . . . . . . . . . . . . . . . 2.6.1 ?Žf . . . . . . . . . . . . . . . . . . . . . . . . . . . 2.6.2 if f¾\ . . . . . . . . . . . . . . . . . . . . . . . . . . 2.7 2.8

2.6.3 for loop . . . . . . . 2.6.4 while loop . . . . . . 2.6.5 case switch . . . . . Portable Shell remote shell . . . . . . . . . . . . .

”+



. . . . .

. . . . .

3 Regular Express 3.1 -RE glob . . . . . . . . . 3.2 . . . . . . . . . . . . 3.2.1 . . . . . . 3.2.2 3.3 . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

. . . . .

+  . . . . . . . . . . . . . . . . . . . C- § . . . . . . . . . . . . . . . . . . . ÃÍC-î . . . . . . . . . . . . . . . . . . . C- § ÀrPšî . . . . . . . . . . . . . . . . . C™ § !Àrî . . . . . . . . . . . . . . . . . . . 3

5 7 7 7 9 11 11 11 11 12 13 14 14 14 14 18 20 22 24 24 25 27 28 28 28 29 31 31 32 32 33 33

CONTENTS 3.4 3.5

CONTENTS

Pšë(address) . . . . . . . . . . . . . . . . . . . . . . . . . . greedyÝregular express . . . . . . . . . . . . . . . . . . . . . . .

4 sed 4.1 . . . . . . . . . . . . . 4.2 addressing . . . 4.3 pattern/hold space, regex 4.4 sed command . . . . . 4.4.1 . . . . . . 4.4.2 pattern/hold space 4.4.3 . . . . . .

+ Ð)fÝ

úƒ Ãͼƒ  ×M

9

. . . . . . . . . . . . . . script . . . . . . . . . . . . . . . . . . . . . . . . .

f

5 awk 5.1 . . . . . . . . . . . . . . 5.2 script . . . . . . . . . . . 5.3 . . . . . . . . 5.3.1 . . . . . . . 5.3.2 awk shell . 5.3.3 Array split 5.4 . . . . . . . . . 5.4.1 . . . 5.4.2 if . . . . . . . . . . . . 5.4.3 for loop . . . . . . . . 5.4.4 while . . . . . . . . . . 5.5 function . . . . . . . . . . . . 5.6 . . . . . . . . . . . 5.6.1 -match 5.6.2 print(f) . 5.6.3 rand() . . . . . . 5.6.4 system() . . . . .

+ Á Žóû› § /Žó Žó Žó p  Ðó ÃÍ×+° ó.ìÕÐ

̀Ðó C™ § ‚ð íáíŒ § Bó Ù

6 perl 6.1

6.2 6.3 6.4

6.5

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

35 35 36 36 37 37 39 41

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

45 45 45 46 48 49 50 51 51 52 52 53 53 54 54 55 56 56

j

Ý §

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . .

ÃÍ+°£]lV . . . . . . . . . . . . . . . . . . . . . . . . . 6.1.1 Žó . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.1.2 f× . . . . . . . . . . . . . . . . . . . . . . . . . . . ?powerÝregular expression . . . . . . . . . . . . . . . . . . . . . ðàÐó . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Ù § . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.4.1 process . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.4.2 jn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.4.3 system call . . . . . . . . . . . . . . . . . . . . . . . . . . module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

uŒ`Äò·®

34 34

57 57 57 58 58 58 58 58 58 58 58

CONTENTS

CONTENTS 5

C+°f´ Žó . . . . . . . . . . . . . . . . . . . . . . . . . . . . p . . . . . . . . . . . . . . . . . . . . . . . . . . . . fB– . . . . . . . . . . . . . . . . . . . . . . . . . . . . ff´ . . . . . . . . . . . . . . . . . . . . . . . . . . . ]º× . . . . . . . . . . . . . . . . . . . . . . . . . . . . ]º . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . —P . . . . . . . . . . . . . . . . . . . . . . . . . . . . ۊ . . . . . . . . . . . . . . . . . . . . . . . . . . . .

7 Bourne shell, perl 7.1 . . . . . . 7.2 Hash . . 7.3 . . . 7.3.1 7.4 . . . 7.4.1 while 7.4.2 for loop 7.5 . . . . . 7.6 . . . . . .

uŒ`Äò·®

59 59 60 61 61 62 62 62 63 64

CONTENTS

uŒ`Äò·®

CONTENTS

Chapter 1



Í@ΜbàÃÍÝ Ìœ9¯Í@ê µŠXÝ xŠ 3† •( îÝ ‚v|IYP¶® lPݶ®… «  %®ç°%® ‡‡KŠàÕscripts #‹ô|à ¶Í ÷ X| ÎtÃ͐GÍ@Xt Š¶ÙõTàPݕ º/lVÝ Õθàé\Ýt{(&Ý scriptÍ@×ߌÿºàÕAŒ ®î^broutineÝ ® #‚ I5ÝßÝé\…ºàÕ»AÑ;×SZaTïi% xŠÎ9° ® Îðð3†ÿœ×ÍgeneralÝ!J »A&àscriptÞ?ÿÕÝ£] ¿àgnuplot®x-y`a% ×ߺ- „‚9‚jìàExceli΍Ž ®ÞÎ×ߝ×O…« ©†€Í¿g9˯à€¬«¬ô^ð9K ` ¬ÎAŒðð®? §œ9g`×ßôºœàº/(macro) Ñword, excel macro 9Í@µÎ×Ëscript scriptsmŠ_ËX||œ"ݶŒ¼Ñ; C/C++mŠ§ºB7 ›Ý®Þ scriptsµ BASIC+ŽÝ¥3ßv¤ÝŽóµ?C/C++µ 3£\.£]3 B7›É¼Éœ à+µÎÝ¥3CPU/ݺՎ› - registers9Ít&µ Î&Í5·ÚxŒ¼Ý»A˜œ/׊ºÃ J̬^b9°ÃÍ Ìô•µÕºJÌ£̧ø†Œ¼ Ý?? N×·Kµäì«×·Ýèºinterface¼¸àQ¡èºî׷ݸ àï interfaceN×·N×·KbÝX|Einstein1ݵÎIYbôÝ Ò«Ä t&§ßÝÃ100Ob×ÍßÏ X|scripts3†Ñ;õ ×°routine jobbœ">ÝÄP Again! AŒ¯Ýé\ÁΜ?9\b݋—¯º:ÿÆÿœp ô0ՏŠÝ£G»A.profile .bashrc9Ëj( 9Λ ºÝ.ïÝÄAŒ¯Š9×FÝÌFT9S ZaE¯bX Qà scripts scripts ” ” configuration Makefile package System Admin perl scripts server scripts script

7

CHAPTER 1.

uŒ`Äò·®



Chapter 2

$Bourne shell 2.1

+

2.1.1

shell

Î#‚

shellÎ×Í#å¸àïúƒ¡šO®¼ÙƕÝ×ÍTàPbߺ .shell ii‘3kernel²«Q¡3‘×·AP&f´Q!9Ëi°¦ E y&¼1shellô©Î¨²×ËapplicationP‚Í@¸«gimp, netscape ‡‡Î×ø݋—©Îºlogin§Œ¼X|€Î|ðÝ×ËTà P àC program¼9ø|Q¯ÝŠ•(Žó

9

2.1.

+

CHAPTER 2.

$BOURNE SHELL





bash USER

-

0x000

exec

ls

0x000

USER

- subshell

bash USER exec exec

exec

KERNEL

0x000 KERNEL

4GB

4GB KERNEL

4GB-

cp

USER

-

0x000

rm

USER

0x000

KERNEL

4GB

- ENVIRONMENT

VARIABLES

KERNEL

4GB

uŒ`Äò·®



CHAPTER 2.

$BOURNE SHELL

2.1.

+

11

¶×wshellÍ@&ðŽxŠÎRÕuserÆÝúƒ¡àforkþŒ¨ ×process Bœunix likeÎ9ß9 ÝQ¡3Š9Íchild processàexecœÆ •9Í ²IP»Als, rm...‡‡X|shell/Iݺ®ÃÎ9øÝ 1. shellPל"8ÇK 2. ƌprompt‡¸àïíáúƒ 3. RÕ¸àïíá 4. fork()×ͱprocess 5. exec()úƒ 6. ƕ9Íúƒê/Õshell 39\ º:Õunix likeÝƕ×ÍPK΢ãexec9Ísystem call¼Æ• Ý 9ή¼Ù躸àïPƕPÝ^×system callÎuserP «kernel Ú;Ý°×Ѽ 3|GMS DOS`‚×^¡ºœÆ•command.com9wPµÎshell €µºþŒ C:\>

‡¸àïíáúƒ9ÍC:µÎèîÐr(prompt)bourne shell;ðpromptÎ$ ©Ä9Ídos shell8 Ý-X| `b͜b(Ý4DOS9Íshell| ゠€(4DOS9ÍshellÍ@Jݜ9unixîshellÝ©P Q«ËÝunix shellÎ f) AŒ ©Îà€¶×¶×°icon¡¼ÝMS-Windows` ‚XÝ`‚Ý command line shellµ%;Ý+«›ã‚ÝÄƕ¨× ÍPÝ^×Î× øΊexec() unix like ÝÙÝúƒø—PÝshellÃÍîtÝƕ²IúƒxŠ€| ”ŠÕ”×°C™¼Æ•9°C™scriptÝ? Ν|'×°•( .9Í ²Iúƒ/)R¼W× ® »A3Windowsì&Æôº'TMPDIR9 øÝê¼Õ£Íêœb°windowsP º.ƕÝ×°õ`jnw3 9…unix likeÝshell scripts+°|bif, while, for loop‡‡¤g×°²I úƒ| ½•(!`b!Ý' ¸ÿ×°^ð ®î?ÿTT Wf€Ýdos shell? ú sed, awk....9°²I Ìò‚òBÕÎýãÝunixÙÄnÝú ƒ ̵ winzipŽWNÍwindowsKº„Ý Ìœ9 ÌÕÎWZÝ / BÃshell programming ÌÝ 2.1.2

ƕshell scriptsubshell

ËË]° • ’R±shellƕshell scripts uŒ`Äò·®

2.1.

+

CHAPTER 2.

$BOURNE SHELL

3êGshellƕshell scripts ’R¨×Íshell¼Æ•Ýscripts3scriptsjtG«GŠ •

#! /bin/sh

Ï×Ë]°Î3shell script ZCjG¼Œshell scriptsŠ\ÝP3£(ôµÎ &ÆÝshell)Q¡.ZCjÝƕJ§Æï×ƕÆ•j]PƕTï § ×Íshell¼ŠÕZCjtest.sh $ $ $ $

test.sh /bin/sh test.sh ( . test.sh; ) exec test.sh

ÏÞË]°Îàúƒ”.”Tïsourceƕ $ $ $ $

. test.sh source test.sh { test.sh; } eval ’. test.sh’

-½3y×°'©b39ÍshellìÝÕó‚’R¨×ÍshellµÎ¨×Í 8Ýt& ôµÎàÏ×Ë]°Æ•ÝscriptŽóÝ'ºÅ( Õæ¼ÝshellŽó 9Í8 ¥Šksh^bsource9ÍúƒX|t?Š àsource Àr( )îà¨×ÍsubshellÀr{ }îàêGshell»A $ ( VAR=’testvar’; ) $ echo $VAR $ { VAR=’testvar’; } $ echo $VAR testvar

©b{ }/ÝVARÝÂ'Íà . Ý]°ŠœT Š3script…« à $ . test.sh arg1 arg2

. arg1 arg2ºµYñ§9ÍscriptÝarg1 arg2¼à . Ý]Pt?Ίƕ Ýscript©Î×$script libraryñ¢ó ¨²AŒ . test.shƕtest.shÒ `ñ§. test.shÝshellô«½Ò uŒ`Äò·®

CHAPTER 2.

$BOURNE SHELL

2.2.

Ž ó Ð óÿ à ; ¶ ®

13

Ž ó Ð óÿ à ; ¶ ®

2.2

Žó¸à

2.2.1

›ŽóÂà

var="value" var=’value’ var=‘command‘

Š.ÂJŒ¼ŠÍþÐr$ $ $ I $ $

var="I am a gyoza" echo $var am a gyoza var=‘ls *‘ echo ${var}

$ var=’$var’ $ echo $var $var

|ŒÝÎè}Îb-½ÝbSrÝ!®àš?ì: 2.2.2

Srquote

2.2.3

Àrݎóã‚

"8îÝdouble quote, single quote, backquoteŠz½ • backquote ‘command‘ 9ÍÎúƒã‚‡y $(command) X|ðð :Õvar=‘commandTïvar=$(command) µÎ.commandƕ”Œ' ›var • single quote 3’ ’/ÝZC;;1¹æø†‚ðb°1ºÐr3ŽS r /1º©„ŒL • double quote 3” ”/ÝZC$ ‘ ”ëˌLº‚ð͸Ý1¹æø • escape char 3\ ¡ÝŽ×C-ô|1¹æø

îÀr{}ÎparameterÝ]° ${var}Îf´?ݶ°AŒ^bŠÍ€ C™|à$varµ? Tè}Îb-Ý€ ̀P¶®9è×Í Kè×}Îb-Ý ̀Žó×°à° • ${var:-value} AŒvarbÂÝ£‚µàæÍÝÂQàvalueÝ • ${var:+value} AŒvarbµàvalueÝ uŒ`Äò·®

2.2.

ŽóÐóÿà;¶®

CHAPTER 2.

$BOURNE SHELL

b£‚µàæÍÝÂQµŒmessage ÂÕÇ

• ${var:?message} var

K¬v®Œ

• ${var:%pattern} var

I ›

• ${var:#pattern} var

I ›

AŒpatternvar¡«ÝI Ù)F/yì^b Ù) AŒpatternvarG«ÝI Ù)F/yì^b Ù)

• ${var/pattern/substitute}

š:×Í»

AŒvarbpatternÙ)µ‚ðWsubstitute

º‡y

# remote shell $RSH /usr/bin/rsh RSH=${RSH:-/usr/bin/rsh}

AŒRSH ^b›Â

9Ë]Pà3bPÝoptionœ?à |ì«9͗P » AŒF¢ó›€J ŽW"-o ¢ó"^b¢óJVAR^b ÎÏ×ÍF ¼Ý¢ó AŒbÂVARµà"-o $1"

# :+ # # VAR # $1 func() { VAR=${1:+" -o $1"} }

9˝|à3[ãC™ÝØI »A TïbÝúƒã/ݔŒ??ΖE­5( ¬&Æ©Št¡«Ý£Íjn(`|à9ͼ[ã ÄFÙÝ ^b% # pattern match9©b3 b t?Šà;àsedf´1 ×F

# :% # find # # bourne shell # ksh bash

PRIV_HOST=fermion-priv PUB_HOST=${PRIV_HOST:%-priv} echo $PUB_HOST (PUB_HOST fermion)

º‡y # ‚ðôÎ 3±ÝKorn shellBourne Again Shellîb BLOCK_DEVICE=/dev/vx/dsk/oracledg/vol_0 RAW_DEVICE=${BLOCK_DEVICE/dsk/rdsk}

2.2.4

•(Žó

û;ݎó AŒBourne shell, korn shellìà $ export var

uŒ`Äò·®

CHAPTER 2.

$BOURNE SHELL

c shell, turbo c shell

2.2.

Ž ó Ð óÿ à ; ¶ ®

15

à

$ setenv var

J9͎óµŽW×͕(Žó3C…«Ý main(int argc, char **argv, char **envp)

&Ɲ|3shell…'•(Žó‚9ÍÂÎNÍã9Íshell forkŒÝP BãenvpK:ÿÕÝ9Íargv, envp¼ÝK3virtual memoryÝì«stack ? îÝ š:k®”àOpen Source toolss8›” X|shellôÄ Î×Í”User spaceÝC program”•(Žóž3C image user spacetì« ô|getenv9Ílibrary function callJÕ X|× 'Žó^b' •(Žó^bð°.Â×å͸ÝP 9\Š¥ŒÝÎæÍÝBourne shellÝexport^bYî $ export var=value

ݶ°X|:Õ×°shell scripts ÝportableRŒKà $ var=value $ export var

2.2.5

×°/Žó

G×ÍúƒÆ•Ýstatus 0î^®Þ3P'Œ…0 îFALSEôîNo ERRORX|PÝexit returnŠ §? • $# îF›shellÝargumentsó • $0 9Íshellúƒ(C • $1 $2 $3 ... functionF ¼Ý¢óarguments • $@ îfunction F ¼ÝXbargumentsº‡y ”$1” ”$2” ”$3” • $* îfunction F ¼ÝXbargumentsº‡y”$1 $2 $3” • $$ îêGÝprocess ID 9\$@ $*Î×ø݊Tsingle guote, double quoteÝ×ø $?à3?Ž fݾÎtðàÝ shell×ôº'×°/•(Žó9°•(Žóºb×°PŠ›º ¼\ã »AmailPàÝMAILb¼€úƒX3¨´êÝPATH‡ ‡ 9°Î¶bash, ksh, cshÝC׶3CP/Ý :•(Žóàenv9 Íúƒ:Žóàsetúƒµ:ÿÕ×ø”Œ uŒ`Äò·® • $?

2.3.

Ðó9jÿà;

2.3

Ð ó 9 j ÿ à ;

CHAPTER 2.

$BOURNE SHELL

ÐóÝLœà#µÎ func() { cmd cmd ... }

FÂôÎ×øݼ§$1 $2 ...$@ ‡à°Î×øÝ ñ§`µÎ func arg1 arg2 ...

Š¥ŒÝΎóÎ^b C×øÝblocal variable;;ÎglobalÝ Ž ÝperlôÎ9ø 2.3.1

ÿà;P

functionÎtŽÝmodulized¶®¼µÎ9Íÿàj Wshell libj à Ý9ÍjݮޫCÎ×øݵΎó§ø3×ÍjLÝQ¡¯½Ýj ¢ï ;ðexport W×͕(ŽóTïàeval9Í/IúƒÆ•×ÍÍshell script¸ÿ 9ŽóÎK:ÿÕÝ

2.4

¥Š ² I  / ˜ ú ƒ

&ÆðàÝls, cp, sh....‡‡9°KÎ×͝ƕj8Ey×ͲIÆ• j shellb×°/˜Ýúƒž3shell…«9°Îbuilt-inÝ/IúƒÎ  àC¶ shell9wP`µ¶3…«Ý cd, export9µÎ bashÍ@bœ9|GݲIúƒ€K‘â ¼®W/IúƒÝ»Aecho, getopts Ä ÝP÷P&ÆÎ.€ÆÌ ²Iúƒ9°/˜ú ƒ|àenable, disable3bash/ã*ĽÝsh, kshT&µ^bÝŠ T 2.4.1

/˜úƒ

f´¥Švp×FÝ/˜úƒb • : ƒ¼ƒ#‚K®‡yCPU/ÝNOP¼ƒ • eval I5༮ËgŽóð • exec ƕØËúƒ¬vð*êGshell(æÍÝƕºð*shell) uŒ`Äò·®

CHAPTER 2.

$BOURNE SHELL

2.4.

¥Š ² I  / ˜ ú ƒ

17

ÿÕ¸àïstandard in("8)íá • set shellÝÞÞ'»Adebug shell scripts • test shell scriptsÝ×+°/Ý?Žf • trap #ÕØËGrÝ § • shift argumentsÝ § : magic numbers Û Š :Ά¢¯Ý3UnixيƕPºœlãjnGÝC™§ magic numberž€ÝBourne ShellÝƕmagic numberÎ : ‚Î #! X|:Õ9Ë |:Ýshell scriptµŠ¤QR¯!`:ôbßJ¼®ÛŠà ‚à#Ý 9°€êYÝshell scriptKΜ•Ý eval ñ ^ C eval|J¼Æ•×ÍúƒĀtðàÝÎJ¼®ËgŽó݂ð xŠ ÎNgƕ×Íshell úƒ€ºevaluate×g:Õb$9͋—ݵ.Âð× g.Žóð* Q¡ƕ×Å9Ëdouble scanÝ]°E×°Žó‚ðœb à . evalΒR¨×Íshell¼Æ•‚Î3ͼ9Íshell/9evaluate× g X|‚𔌝|1ºì¼ »AAŒ&ƊËg‚ð • read

count=1 var1=I var2=am var3=a var4=gyoza while [ $count -lt 5 ]; do eval "echo \$var$count" let ’count=count + 1’ done

|×àŽ;1. 2. 3 ....Š®ß×ͱŽóvar1 var2 var3....Q¡E var1 ãÂÍ. Ï×ÍvarºÕX|àescapeC-\ Q¡ÏÞ gºÕ`ŠÕ £AŒŠëg|îŽó‚ð3ו/ŠX÷? :Ï evalxŠà¼evaluateƕ×Íshell scriptj| C×ø¶Wœ9Ý ÿ àshell script3!×ÍshellìrunJŽó3hshell/;;b[ count var2

$ eval ". foo.sh"

ÄAŒŽóH9(CºÆÚ uŒ`Äò·®

¥Š²I/˜úƒ

2.4.

CHAPTER 2.

$BOURNE SHELL

exec

º. êG Ý JÍ J*ðW¡«ÝúƒÍ@9µÎà 9Í Hð*•݌LÎ×øÝ tð:ÕÎ3 /.xinitrc9 Í Hð*W »A exec twm X|AŒ¯3shell ƕ exec ” ” shell process exec() system call scripts window manager exec cmd

‚cmd9ÍúƒD3µº/Õloginœ. JÍshellðÕcmd¬Q^ bcmd9Íƕj X|ƕPÝ]°ËËÎ×øÝ $ exec cmd $ cmd

w3scriptsÝƕ Qô×ø Äexec3scriptb¨×Í8 ¥ŠÝàHµ Ϋfile descriptorÝ=” 9͇쫼D¡ read $ read input read from standard input $ echo $input read from standard input

Jº‚39\‡"8íáíáC™ŽW$input9͎óÝ set set

ÎJ¼'9ÍshellÝƕ•(Ýf´¥ŠÝscriptºàÕÝà • set -- Ñð:Õ-¡«Îoption¨3Îoption ‚Î×Íúƒ¢ó A-1 -2 ... • set -a 9\|¡ŽóŠ›ŽW•(Žó • set -f ŠŠÕj(Ý©„C-»Awildcard *ŠÕ Xb݌¤Ý • set -x debug shell scripts

׊àexitÒshell,ͼ¶Ctrl-D(eof)ô| • set -o noclobber n*I/O0'ãoverwritejn • set -o notify shell”@` ×background jobÝstatus • set -o noglob n*wildcardC-ŠÕ A * ? [ ] • set +o .-oÝD'E® uŒ`Äò·® • set -o ignoreeof

CHAPTER 2.

$BOURNE SHELL

2.4.

¥Š ² I  / ˜ ú ƒ

19

n*-v -x –ëËó4 set -- Tïset - ððà3shell scripts…« set -o ΜðàÝ»Aset -o vi'shellÝE®]Pàvi]° ã/îÍúƒµÎ¶ESC¶kC set -o emacsµÎàemacsÝ]° • set -

test test

Î×+°Ý?Žf9Í3ì«D¡

trap

RÕØÍsignal`shell†ÝET ;P $ trap "command" signo ÍsignoÎ 1) 5) 9) 13) 18) 22) 26) 30)

cyril@grill:~$ kill -l SIGHUP 2) SIGINT SIGTRAP 6) SIGABRT SIGKILL 10) SIGUSR1 SIGPIPE 14) SIGALRM SIGCONT 19) SIGSTOP SIGTTOU 23) SIGURG SIGVTALRM 27) SIGPROF SIGPWR 31) SIGSYS

3) 7) 11) 15) 20) 24) 28)

SIGQUIT SIGBUS SIGSEGV SIGTERM SIGTSTP SIGXCPU SIGWINCH

4) 8) 12) 17) 21) 25) 29)

SIGILL SIGFPE SIGUSR2 SIGCHLD SIGTTIN SIGXFSZ SIGIO

»A

$ trap "" 2 $ trap "rm $TMPFILE" EXIT 1 2 15

AŒ””ÝcommandJîshell §9Ísignal 2rµÎINT;ðµÎ¶ÝCtrlCÆ\shell scriptÝƕ15µÎ TERM(processkillÝ):p×FÝ» trap_init() { trap ’

scriptcleanup [ "$SCRIPT_DISP" = ABORT ] && exit 100 [ "$SCRIPT_DISP" = PASSED ]; exit $?’ EXIT if [ -z "$__TC_INTERACTIVE" ] then for sig in HUP INT TERM; do trap " trap - HUP INT TERM; echo ’Signaled - cleanup after script ...’ >&2; scriptcleanup $sig; kill -$sig $$; exit 101" $sig done fi trap : PIPE

uŒ`Äò·®

¥Š²I/˜úƒ

2.4.

CHAPTER 2.

$BOURNE SHELL

}

9Í»ÝG«AŒ8ÕEXIT9ÍsignalµÆ•scriptcleanÕexit $?Ýcode µÎŽquote/݋— AŒ$ TC INTERACTIVEÎèC™µÆ•ì« Ýsignal § t¡AŒÎSIGPIPE(13r)µ†¢¯(Ar:) shift

Îà¼. ¼ÝargumentsÉ×͛É shift n Én͛É shift|J¼ àøÄ10Í|îÝargrments. $1 ... $9©b9͂ ¼:×ÍshellÝqueue listÝappend shift

# list_append list_name item ... - append items to a list list_append() { _list_a_name=$1; shift eval "set -- \${$_list_a_name} \$*" eval "$_list_a_name=\$*" }

2.4.2

²Iúƒ

b°²IúƒðàÕ • basename J*—j(Ý § • echo ŒmessageÝ]° • find 0jn • getopts §F ¼Ýarguments«CÐP0Ýgetopt()œ • xargs pipe`ÝúƒÆ•¢óargumentsÝ § ¨²sed awkºbÝ+Û basename

RŒj(—j( Ì $ basename foo.c .c

J—j( .c º„* uŒ`Äò·®

CHAPTER 2.

$BOURNE SHELL

2.4.

¥Š ² I  / ˜ ú ƒ

21

echo

ÎŒ‹—ÕÇKÝWð(ôbprint, printf|à) 9\ŠýÝÎsh, /ÝechobashÝ×øX|'b°×ø echo -n "messages" Šð•(newline) echo -e "messages\c" ŠÕescapeC-\c‡y-nà° echo -e "\t messages" tab3messagesG

echo ksh

FÙsh, kshÎ^b-n -eó4Ýà#àechoµ? echo "messages" Šð•(newline) echo "messages\c" ŠÕescapeC-\c Šð•(newline) echo "\t messages" tab3messagesG getopt

getoptsÍ@Îksh, bashÝ/IúƒgetoptÎËݲIúƒ 9œ C… Ýgetopt()š:Í» while getopts :dvt:n: c do case $c in d) DEBUG=yes ;; t) TYPE=$OPTARG ;; n) NUMBER=$OPTARG ;; v) VERBOSE=’yes’ ;; esac done

ÍAr:Î19Í¢ó׊b«½Ý¢óÂ^bAr dvî¡«^ bñ½¢ ó »Atð:Õ-vÎ1Pƕ`Îverbose modeµÎ9ø $OPTARGµÎ«3¡«Ý ¢ógetoptsŠ›Q& §?¬v×Í×ÍÝó

$OPTARG¼€ôb$OPTIND«C libraryÝజ find

´0jnàÝPúƒ uŒ`Äò·®

¥Š²I/˜úƒ

2.4.

CHAPTER 2.

$BOURNE SHELL

0 0 0 0 0 0

find . -name "regex" find / -type d directory f plain file l symbolic link p named pipe file b block device c char device find . -perm 755 find / -user cyril gzip ‘find . \! -name ’*.gz’ -print‘

ƒ

not !

bÝshellŠ\ . !b©½ŒL»Abashîã/|GÝú

find -name -type -o -name

3scriptœ9`ÎKÎñ^C-®Þð:Õ\`KŠÕ9Îñ^C- 3script ()ôb©½ŒLî’R¨×Ísubshell¼Æ•X|$Õ()`ôŠà ñ^C-Tï)sed awk×R¸à`ôÎ×øݼ§ xargs

༠§×°íŒ”ŒŠ¼ ¨×ÍíáÝarguments$ÕÝ®Þ »A

xargs

# find /usr/include/ -name "*.h" | xargs -n 2 diff

μbËË W팎WdiffÝargumnets

-n2

# find /usr/include/ -name "*.h" | xargs grep ’#ifdef’

Ñð/ÎíŒÝ×rZ8ݔŒbàxargs`Î×Í×Í;›¡«Ýúƒ # find /usr/include/ -name "*.h" | xargs -i cp {} ~/include/ -i  { }|.findÝíŒÝN×Í WcpÝÏ×Íargument /.µ| WÏ ÞÍargument Í@find…«b-exec9Íó4¡«ô|à{ }î×Í×Í ;›¡«P‚Î ×rZ0Ý;›¡«P # find /usr/include/ -name "*.h" -exec cp {} ~/include/

2.4.3

Žó.

xŠÎJ¼®counterÝbœ9Ë]°ì«+ÛëË bashbÍ/˜ Ýlet »A uŒ`Äò·®

CHAPTER 2.

$BOURNE SHELL

2.4.

¥Š ² I  / ˜ ú ƒ

23

let ’x = x + 1’ let ’x = x * 1’

¥Œ!!9\‡rŸ\ÝxãÂ`àþÐr‚v3Žquote/ô|bè } kshôb/˜ÝÄ9ÎNËshellKbÝ f´1 Ýportable®° Îàexpr9ͲIúƒ š:» if [ "$KSH" ] then eval ’ add() { result=$((${1} + ${2})) } sub() { result=$(($1 - $2)) } mul() { result=$(($1 * $2)) } div() { result=$(($1 / $2)) } inc() { eval "$1=\$((\${$1} + ${2:-1}))" } dec() { eval "$1=\$((\${$1} - ${2:-1}))" } ’ else add() { result=‘expr $1 + $2‘ } mul() { result=‘expr $1 * $2‘ } div() {

uŒ`Äò·®

 0'

2.5. FILE DESCRIPTOR I/O

CHAPTER 2.

$BOURNE SHELL

result=‘expr $1 / $2‘ } sub() { result=‘expr $1 - $2‘ } inc() { eval "$1=\‘expr \${$1} + ${2:-1}\‘" } dec() { eval "$1=\‘expr \${$1} - ${2:-1}\‘" }

9î«LÝ×°—P|3script…«×ø ñ§×úƒñ§ Î×Ísubshellƕ1+1¬vF/”Œì«»¯&R&Ýbasic P $((1+1))

i=0 while [ $((i=$i+1)) -lt 10 ]; do echo $i; done

Ä$(( ))9«${VAR%value}×ø©bksh bashbt?Šà3mŠ portable ÝshellPî —PÝposition parameters $1, $2 ....«¿ðscriptPæJ ×ø AŒŠ?9Ýó.»AóFݺÕTïsin log‡Ðó¸à µàbcõawkÏ kshbashKYîtypesetÄFÙÝsh¬Yîbashbdeclare9Í/I úƒ 9ËÍKÎJ¼L9͎óÎ#‚P²Ýœ C݅×Ä Ýportableà µŠàÎàtÃÍÝshµ?AŒË݊¶ÿœÓ µàperlÏAŒ&ðÝ ¯µàCC $ typeset -i int_var $ declare -r constant

'WJóAŒ›C™Jint varݺÎ0AŒà-r JconstantÝ ¨3R;Ý

int var

2.5

File descriptor

I/O0'

×ÍPtÃÍݺŠ›@ëÍjE®`8ET݂rµÎfile descriptor Í@ôµÎ®¼ÙNgŠÕÝfile descriptorÎper processÝ • 0 standard input ;ðµÎ"8 uŒ`Äò·®

CHAPTER 2.

$BOURNE SHELL 2.5.

I/O0'

FILE DESCRIPTOR

25

;ðµÎÇK buffer I/O • 2 standard error ;ðµÎÇK &Ɲ|àI/O0' • 1 standard output

$ cat file1 > file2 $ dirs 2>&1 > /dev/null

ƕdirs`X®ßÝstandard erroróÕstandard outÕAü/dev/nullœ µ Î#‚ô:Õ exec tðà3file descriptorÝnÐ9… $ $ $ $

exec exec exec exec

3> $LOGFILE 3>> $LOGFILE 2>&< infile

Í&ŒL5½ ×Í3rfile descriptor8Ey$LOGFILE.standard errn* .êGshellÝstandard inputŽWinfile $ cat something >&3 $ read <3

¨3 9Í µ8Ey ÝX|cat somethingÝ/ºÕ œ ¥Œ 0'ÐrÝè} ×°¥ŠÝI/O0': > ¥±0'¬v.jnéè(&ËÎ?:-)) >> .”Œ0'¬vappendÕjn¡ < ¥±0'standard input >&n .standard outó›file descriptor n <&n file descriptor nJ‹—›standard in >&close standard out <
Š¥ŒÝÎb°¡«©#jnbÝ#file descriptorb #file descriptor`bè} Š›ftpÝscripts3œ\œ\|G .ÝftpìÎ b(ÝXçì Ā©º3– wêÝDãX|&Ƶ§é\3 –`cron jobŠ›Q&Æftpbb #!/bin/ksh # A script to automate FTP transfer HOST=ftp USER=user

uŒ`Äò·®

2.6.

ø×?Žf

CHAPTER 2.

$BOURNE SHELL

PASSWORD=password FILENAME_PATTERN=remote_files REMOTE_DIR=/usr/doc LOCAL_DIR=/usr/local # -i = non-interactive, -n = disable auto-login ftp -i -n <
¥Œ<<Ýà°ftpÝinputº×à\ÕHERE copen, user, cd, mget K ÎftpÝúƒÄô|. 9°ftpúƒ¶W×ÍjnQ¡ftp < jnô •

ø×?Žf

2.6 2.6.1

?Žf

3Bourne shellÝ/Iúƒ…«b?ŽfÝ+°test›if whileà Tï

test condition [ condition ]

ÝautoconfŠƒprogrammerf´‡Kàtest àÀrconditionÝ ]°ÀrÝచ¥Œè} »A jn?Žf test -f /etc/file jnÎÍ×jnÎ̀©„jn[ [ -e file ] jnD3[ [ -d /etc/ ] êD3[ [ -s file ] jny0[ [ -r file ] jn\[ C™?Žf [ "$string" ] stringb‹—µ/true [ -n "$string" ] stringb‹—(non-zero)/true [ -z "$string" ] string^‹—(zero)/true [ "$s1" = "$s2" ] s1 ‡y s2`/true uŒ`Äò·®

CHAPTER 2.

$BOURNE SHELL

[ "$s1" != "$s2" ]

óÂf Tb9Í-‰

[ [ [ [

$num1 $num1 $num1 $num1

-eq -ne -lt -ge

$num2 $num2 $num2 $num2

] ] ] ]

s1

2.6.

ø×?Žf

27

‡y s2`/true

num1

8‡ num2 true ‡ num2 true y num2 true y‡ynum2 true

9¥f

[ ! -f "testfile" -o ! -r "testfile" ] [ test condition -o test condition ] ! not -a and -o or

î î



;ðf´ðàÝêbportableݵÎî«×°à° YÌî¼1àÀrconditionf ´?:œ9ß ÝautoconfÝ+°portableRŒ ¼àtestݶ°?ŽÝ ”Œ Qw3$?0îW ̀Âî´? 3shell scriptôb:Õbßà if [ "x$VAR" = "xvalue" ]; then .....

¼®$VARÎÍÎèÝ?ŽLͯAŒ?ŽÎÍ èC™ ?ŽÎ£Í Š†%‚9øµº®Ëg?Ž¼à9ø®f´Bz ¨²9«perlC™óÂ?Ž|ƒ€«perlâ?8D‚vperl^b9perl+° if ($str1 eq $str2) if ($num1 == $num2)

t¡bÍf´º×RŒshell perl cÝ-²¼(߀ÝBœ&Î9ø B |perl ÃãeqÎCX|G¡Îstring==ÎÐrX|G¡Înumber bourne shellÎMhâ?xÅeqŠÍ-Ðr==ŠK×Í=) C+° if (!strcmp(string1, string2)) if (num1 == num2)

2.6.2

if

f ¾ \

if test;then cmd1; elif test; cmd2; else cmd3 fi

uŒ`Äò·®

2.6.

ø×?Žf

CHAPTER 2.

$BOURNE SHELL

if test then cmd1 ... elif test cmd2 ... else cmd3 ... fi

!ø¥Œ¶Wו`Ý5r›HLÍ3¶Makefile`ºàÕ ¨²€Ýelse ifÎelif «CÝelse if×ø‰ ¨²bˍŽÝifà° [ "$VERBOSE" ] && echo ’everything’ && îF/true`ƕ&&¡ «›® [ "$VERBOSE" ] || echo ’nothing’ || îF/false`ƕ||¡ «›® 9\bFŠ¥Œ AŒÎèC™F/false 9Í@œ [ "$var" ]

[ -n "$var" ]

;ðÀr…«Î9°¾\Ý]P¬Í@Ng€AŒ:Õbúƒ‚ðÝP  ºœÆ•×gúƒ ¬ÎBœ€ÎC|3if while…«Æ•P (expression)/return €X/¼ÝÎúƒÝstandard outX| |Ž½!`ƕúƒ Q¡Š¾\ƕWÍ¼Xì×M§‚® ÄbÝúƒWÝº3standard out Œ×ÀC™&Ɲ|¿à9øݕ

¼ ®¾\»A [ "$(find . -name gyoza.txt)" ] && echo "I Find It !!!"

à$(cmd) ‡yà‘cmd‘AŒ0ÕݺŒ9Íjn¼X|ÔSr…«” ”b  Àr µ/trueCAŒ^bÔSr AŒ©b×ÍC™Jº WC™ÕG true X| uŒ`Äò·®

CHAPTER 2. $ $ 0 $ $ 0

$BOURNE SHELL

2.6.

ø×?Žf

29

[ 1 ] echo $? [ 0 ] echo $?

AŒbËÍ|îJshell.findóŒ¼ÝC™ê WúƒœÆ•€µs ß ý0Ý 2.6.3

for loop

for var in $list; do cmd1; cmd2; done for var in $somelist do cmd1 cmd2 done

¥Œ¶Wו`Ý5r›HLÍ3¶Makefile`ºàÕ listÎshell…ðàÝ ×Ë]°µ©Îœ9Ž›àè}Ttab5Ý£]µÎ »A ME="I am a gyoza"

µÎ×Ílist(bashÝman pageàlistî×Àcommnands .wordî9… Ý bÝhTïksh, shÝman pageê×ø X|&œ‡KœL9° (Þb`ÎÊ¡9°^bŒL RÕkey pointf´¥Š)for B–|×g.× Í-ô;›G«Ývar ME list

for ELEMENT in $ME do echo $ELEMENT done

µºŒ¨ I am a gyoza

¥ŒþÐr'Žó¸àŽóÝ-² uŒ`Äò·®



2.7. PORTABLE SHELL REMOTE SHELL CHAPTER 2.

2.6.4

$BOURNE SHELL

while loop

while test ; do cmd1; cmd2; done while test do cmd1 cmd2 done

!ø¥Œ¶Wו`Ý5r›HLÍ3¶Makefile`ºàÕ 2.6.5

case switch

case $var in *)cmd1; cmd2 ;; xx?)cmd3; cmd4 ;; esac case $string in *) cmd1; cmd2 ;; xx?) cmd3 cmd4 ;; esac case $answer in [Yy]) echo ’yes’ ;; [Nn]) echo ’no’ ;; esac

Ýà° CÝÎJóÝcase switch‚Ν|bC™Ý‰ Í Ð)ÝC™fàglobbingÝ]PôµÎwildcard *, ?, [ ] bÝhî ¶regular expressÎý0Ý¥Œàו¶ŒÝ]° case switch

2.7

Portable Shell

remote shell

remote shellƕÎËÝ.GÐÝstandard out =Պ Ýstandard out X|€  ×telnetP Í@AŒ ®•(@©3bashî£ôàÊ×°¬¿¬Ý Ä AŒ®development`ŠÊÕportableݶ®TŒàtæÝshµ? uŒ`Äò·®

CHAPTER 2.

2.8

”+

$BOURNE SHELL

2.8.

”+

31

×ýãàshellÎBourne Shell¡¼;¨ŒKorn Shellœ9€×ÄÝ /  f´‡Kàkorn shell¶scripts¨²bBSDÝC shell c shellôCW×ô± LÍ3œ9system admin¡¼tcsh œ9ýÝ©F Bourne Again Shell.bÝ^Ý©FZZÚÚw3×R´GNU/Linux± OD×‚Ý /œ9‡KbashĊ¥ŒportableÝshell scripts¶® sh, ksh bashÎ !×HÝ9¿Í+°f´# tcsh cshΨ×H -œ9× 1¼sys admin‡Kàc shellFÙÝprogrammeràshÝ´9

uŒ`Äò·®

2.8.

”+

uŒ`Äò·®

CHAPTER 2.

$BOURNE SHELL

Chapter 3

Regular Express 3.1

+-REglob

regular expressÎ×Ëî]°à×°©„ÝC-¼î×°é\…Ý©„Œ L¬v† ´0Ý×ËøPfE (pattern match) 3MS dos/windows ôb8 ÝC-»A * ‚XbCX|¯àdel *.* µ|B *Xbjn* µ§wildcardC-Ä93shellÝ §©Î§†globbing ¬Îregular expressÍ@9 QÎUnix.œÝUNIXîÝregular express?ú‚ vÊàyœ9Unix 8›…« grep, sed, awk, vi, emacs perl...‡‡ |1regular expressµÎ¸àUNIXÝ·~ Ċ¼.unixš.DOS£ general‹—›Ý CP…« §regular expressAŒÎPOSIXÝÙJà regcomp() regexec() System VÝbregcmp(), regex()BSDÙbre_comp(), re_exec() 3shellÝpattern match§globbingshellÎ-ÿregular expressÝ ;ðà y­5(Ý ? * [] ÝfEETàfnmatch()¼ § Ä9Ί—Ý¥ F©Î|¡ $àC¶P`|Õà#‚function call ;ðœ9¸àregular expressÝ`¡ºà×E//ôœ /reg express/

¼î0Õ){reg expressfÝC™perl…«1Í@Î m// s///

îmatchsÎsubstitudeÄm|6¯¶µŽW//Ý ;ðà° Îm//úƒ s///úƒúƒð:ÕÝb • p -> print ;ðôචm

33

3.2.

C- §

CHAPTER 3. REGULAR EXPRESS

9;ðΫ3múƒ¡ Ð)ݵB* • c -> confirm ;ðà3súƒ ˜®ÎÎˊ゠• g -> global ;;ð . matchÕ`/©bÏ×ÍÐ)Ýb[ • i -> ignore Ѷ Äô× grepúƒµ^bàÔSrµ|Ý anyway,©Îœ9K Î9øî • d -> delete

3.2 3.2.1

C- §

ÃÍC-î

C-µÎŽ××ÍzZCÒÝ §¼ÍÃÍÝC• . ‚Œ”×Í”C-tÝð•newlineC-Äawk|matchð•Bœ • ? ‚”G«”C-Œ¨0gT1g • + ‚”G«”C-Œ¨1g|î 1 2 3 4 ... Œ¨return false • * ‚”G«”C-Œ¨0g|î 0 1 2 3 ... 9\.ïf´ðÙÝý0Î3shellìÝwildcard * ÝêY| ©Š›Í* µ‚XbC-Í@Î ? + * KŠG«¤g . ¼¸à‚ŒC• ^ ‚•´ • $ ‚• • \ ñ^C-(escape)㏩C-݈LàÝ 9\f´Š¥ŒÝÎC3•´RÝ^• Ý$3•Ýcase5ò! Ýregular expressTbÝPº.9ëË W!Ýregular express 9º ×ø‰Äbݺ • /^#/ b#3וÝÏ×C-` µ/TRUE • /^bag/ bag3•´Ý• • /bag$/ bag” ݕ • /bag/ bag3 ݕ ÄbÝP §^b9‚} sed • /b.g/ îbag beg bugK• • /b\.g/ îb.g • /^..g/ bag beg bug xxgKÐ) ¬×ŠëÍCÒ • /^.*g/ b¢C-ÝQ¡bÍgÝK|/true uŒ`Äò·®

CHAPTER 3. REGULAR EXPRESS

3.3.

C™ § -  ! À r  î

35

• /beg*/ be, beg, begg, beggg, ....... • /beg+/ beg, begg, beggg, begggg, ...... • / */

3.2.2

èçC-ô•

C- § - ÀrPšî

/Ý×”Ž×C-”Ð)µ/TRUE • [^ ] []ÝD[Œ â[]/Ý׎×C- /true X|9\^3[]/ b!݌L • [1-10] -r3[]/|î×ðPšàÆÕWTi X|AŒŠ î-rÄ6w3Ï×Tt¡C• w{n,m} =C-Œ¨î° fà /.../?à «L T XÝtableÝజ îb”=”Ð) wCŒ¨”=” ngÕmgE Kº/TRUE • 0{3,} 0‹KŒ¨3g -> /xxxx000xxxxxx/ 3C™ì{} ()ÎîËÝ9°C-Ý [ ]ºregular express W×Ë ºÕX|ŠÝàñ^C- ŽW\{ \} \( \) • [ ] []

A

3.3

C™ § -  ! À r  î

×°C™Ý §î

• ( ) Group operator

Tï Tï  Î Ý ©b×°8›AegrepbYîX |3à8›Ý `Ä6ἀ §Ý æ • & î0ÕÝC™ • \1 \2 \3 ... ‚s///G«àÀr\(\)ÀR¼ÝC™ 9;ðôÎ0 ÕÝC™Ä&©b×Í à \1 \2 \3 |bœ9Í \1 Ï×ÍÀr/C™ \2 ÏÞÍÀr/C™ ;ð\1 \2 \3Îà¼EmatchÕÝC™Š §`àÝ /[Yy]es/ Yes õ yes /80[23]?86/ 8086 80286 Tï80386 /[A-Za-z0-9]/ C-|b9øÝ=î° /compan(y|ies)/ company companies /0\{3,\}/ î0ŠŒ¨ëg|î uŒ`Äò·® • (str1|str2|str3) str1 str2 str3 () | extend regular expression regex regex

3.4.

Pšë(ADDRESS)

CHAPTER 3. REGULAR EXPRESS

ÞæÍݕîÀr .ËÍC™EŸ ¥Œ\1 \2Ýà° Í 9°ðà3‚ð(substitue) ¥ŒÀr3G«b!ŒLX|Ä6à\¼escape

s/.*/(&)/ ( ) s/\(str1\) \(str2\)/\2 \1/ & \1 \2 \3 ...

3.4

Pšë(address)

3sed, vi‡editor…&Ɲ|¼Š §Ý•Pš 9˼Š §Ýf• TØðrangeô§address(ë) LÍÎðúƒœðà range(addressing)s///

sed $ sed ’1,3d’ file

3ÏוÕÏë• „*J•

vi :%s/xx/yy/g

.JSZaÝxxðWyy

ðàÝPšÐr • , •ó§× 1,5 îÏוÕÏ"• • 0 tîו • . êG• • $ t¡×• 5,$ îÏ"•Õt¡×• .,$êG•Õt¡×• • % JSZaô‡y1,$ • x-n x?îón• .,.+10 îêG•ÕêG•è• • x+n x?ìón• 3.5

greedy

Ýregular express

XÛgreedyÎ1AŒ×•…«Ð)regular expressionݵbœ9ôµÎ ! `bœ9patternKÐ)`;ðºœ1TÝÐ)tÝ£ÍpatternÄ ¬ Î&ƊÝLÍ3HTMLÝtag §î»Aà/t.*t/œ0 this is a tag3 !ו… bôbgreedyÝ §©bperlbf´ŽÝ] °9Þ3perl…«—Õ

uŒ`Äò·®

Chapter 4

sed 4.1

+

Î×ËStream EDitorôµÎ;›¸×™£]ø«úƒW_ìݛ® 9œÊ)Š›;Ýscripts®¼ sed

file -> stream -> sed -> stream -> file

ãy¸Ä6bÍin §¡bÍoutX|!`;Íjn Ä6 § jn¡XŒW±j(.jl*.±j;(Wj ê. €/íŒ Îstandard outX|ð:ÕÝ]°Î $ sed ’sed_syntax’ old_file > new_file $ mv new_file old_file

Äsed;ðÎà¼EC™Ý §•îÎ ×editor¼modifyjnÝ ‚ vBœÎוו §ÝX|èç, tab, ð•9°C-œ¥Š sedÝ×PÎ sed [address],[address][!]command[args] file

Íaddress,commandàŽSr’xxx ’‘œ addressµÎî«regular expressÝ ‹—ðàÝúƒbd(delete), s///(‚ð) ×°Ž» $ sed ’s/yes/no/g’ file .jnyesðWno $ sed ’/save/!d’ file .^bsaveC¿Ý•„* $ sed -e ’s/\(.*\)\(#.*\)/\1/’ xxx.sh .#¡«Ýۊ„* Í-eÎðàÝ×Íoption;ðÎà3ËÍ|îÝó4` Íãy( )b ©½ŒLX|mŠDEaescape×ì 37

4.2.

4.2

Ð)fÝADDRESSING

CHAPTER 4. SED

Ð)fÝaddressing

addressÎsed…Ý©„à+à¼'Ð)fݕ|-E¸Æ•_ìú ƒ Ð)fÝf¼]°b1. range(Pš) 2.regular express sedÝaddresstÝGregular expression+ÛÝ 1,3 . $ %9Ëî°²  |à#à /regex/0Պݕ $ sed ’2d’ file 0ÕÏޕ„* $ sed ’/delete/d’ file 0Õdelete9ÍC„*J• $ sed ’/RE/,$d’ file bREC¿Ý•Õjn ;;„* $ sed ’/^$/d’ file „*èç• $ sed ’/START/,/END/!s/xx/yy/g’ file > file1 .xxðWyy

4.3

pattern/hold space,

AŒbËÍf||-e

9regexfscriptj

$ sed -e xxxx -e xxxx file

»AÞۊ•ŽWèç•Q¡B*Xbèç•

$ sed -e ’s/\(.*\)\(#.*\)/\1/’ -e /^$/d file xxx.sh sedÍ@NgK.וwÕpattern spaceQ¡E€E® ƕ”Œw Õpattern space9Í2]AŒb -e µ#½Epattern spaceݕ†scriptÝ Æ•X|?¿ÍfÎb5Ý †ו¡¼×ÅX|t;àÝ× PTŒÎ [address],[address]{ command[args] command[args] ... }



[address],[address]{command[args];command[args];...;command[args];}

Nוcommand8 ybÍ-eÝ®àº.”ŒwÕ×Ípattern space | ¶W×Ísed script fileQ¡à-f ƕ $ sed -f script_file file

TïNÍcommandÝt¡«ŠwÍ5r; ¨²sedbÍhold spaceÎÍõD ‹—Ýbuffersedb°úƒ|¿à hold spacepattern spaceœ vi…« Ýyy dd wÕ×Í:ŒÝ bufferàpúƒ.¸§Œ¼ uŒ`Äò·®

úƒ

CHAPTER 4. SED

4.4

sed command

command

4.4.1

b25Íf´ðàÝ

4.4. SED COMMAND

39

úƒ

Ãͼƒ

µÎ.9¿Í_ìúƒ.?¦ • Append a\ 0Õaddress¡appendXba\ ¡«XbC™ • Change c\ ;Ž×ðZC • Delete d B*regex0ÕÝC™£×•BœÎJ•B*‰ • Insert i\ 0Õaddress¡3G«insertC™ • Substitution s/// ‚ðÎtðàÝ • Translate y/// |×ÍC-×ÍC-®!݂ð a\ úƒi\úƒ¥Œa\ i\ KŠð•ŠáÝZCAŒŠ ÝZC bð•Šà\ 9ÍÐrîð•AŒŠáÝZCb\ | à\\¼escape*\Ä9\bœÝ®Þ ôµÎAŒZC…«!`b\ ’§ ‚ð ãyshellݎSr ’ ^ð°^*9Í©ÿ¨¶scriptjŠXš: » Ïו t¡×•

cyril@gyoza:~$ cat last

ZŽŽ: Ïו ZŽŽ: t¡×• ZŽŽ:

cyril@gyoza:~$ sed ’a\ > > ’ last

ZŽŽ: ¬vƌð°øÄו::†¢ §` øÄו` º§‚ø §9øÝ®Þ

cyril@gyoza:~$ sed ’$a\ > > sed > ’ last sed: -e expression #1, char 93: Unterminated ‘s’ command

ZŽŽ: ¬vƌð°øÄו::†¢ §` øÄו`\ º§‚ø §9øÝ®Þ Ïו uŒ`Äò·®

cyril@gyoza:~$ sed ’$a\ > > sed > ’ last

úƒ

4.4. SED COMMAND

CHAPTER 4. SED

t¡×• ZŽŽ: ¬vƌð°øÄו::†¢ §` øÄו` sedº§‚ø §9øÝ®Þ ¬“½˜»P­×ð r

cyril@gyoza:~$ cat address.txt 270 <Michele’s Address>

¬“½–n­ ×ð10r

cyril@gyoza:~$ cat insert.sed //i\ 100 Gyoza Blvd\ San Jose, CA

¬“½˜»P­×ð r

cyril@gyoza:~$ sed -f inser.sed address.txt 270 <Michele’s Address> 100 Gyoza Blvd San Jose, CA

¬“½–n­ ×ð10r



9Íúƒ«a\ i\ œ ©b×FŠ¥Œ µÎAŒŠ;ŽÝZC ¬œ9•J adressÎÍrange 1,109ø`XbÝrange•Kº´¬v© bו;ŽÝ

c\ change

Ïו Ïޕ t¡×•

cyril@gyoza:~$ cat last first line second line last line cyril@gyoza:~$ cat change.sed 1,2c\

Ïו«ÏޕK„*Ý Ïו«ÏޕK„*Ý t¡×• last line

cyril@gyoza:~$ sed -f change.sed last

uŒ`Äò·®

úƒ

CHAPTER 4. SED

4.4. SED COMMAND

41

¶Ž¶ .ÏוÕÏè•Ý¶Ž¶

$ sed ’1,10y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/’ lower.txt

‚ðÝúƒbœ¥ŠÝÏÞ· §AŒ3ו/ÝC™Ù)Š‚ðÝbœ 9 Í£‚/ºàÏ×ÍÙ)Ýð*AŒð*©ݵ3¡«îŠ Ý Ï¿ÍIð*àg9Íflag Ïו Ïޕ t¡×•

cyril@gyoza:~$ cat last first line second line last line

Ïו Ïޕ t¡×•

cyril@gyoza:~$ sed ’s/first/line/1’ last line line second line last line

Ïו Ïޕ t¡×•

cyril@gyoza:~$ sed ’s/first/line/2’ last first line second line last line

Ïו Ïޕ œ9• t¡×•

cyril@gyoza:~$ cat lines first line second line multiple line line last line

Ïו Ïޕ œ9• t¡×•

cyril@gyoza:~$ sed ’s/line/row/2’ lines first line second line multiple line row last line

Ïו Ïޕ œ9• t¡×•

cyril@gyoza:~$ sed ’s/line/row/g’ lines first row second row multiple row row last row

4.4.2

pattern/hold space

Ý §

݋—Î#‚ • h .hold space…Ý‹—z*.pattern space݋—copy›hold space uŒ`Äò·® • l list pattern space

úƒ

4.4. SED COMMAND

CHAPTER 4. SED

.pattern space݋—3hold space‹—¡« • g .pattern space…Ý‹—z*.hold space‹—J/›pattern space • G .hold space݋—3pattern space‹—¡« • p Œpattern space݋— • x øð(exchange)pattern spacehold space l«pÝ-½3E&ASCIIÝ § • H

Ïו Ïޕ t¡×•

cyril@gyoza:~$ cat last first line second line last line

Ïו Ïו Ïޕ Ïޕ t¡×•

cyril@gyoza:~$ sed ’1,2p’ last first line first line second line second line last line cyril@gyoza:~$ sed ’1,2l’ last \262\304\244@\246\346 first line$ first line \262\304\244G\246\346 second line$ second line last line

Ïו Ïޕ t¡×• 9\|Epattern spaceb?Ý݊Ïו Õpattern space :Õp.Ï× •Œ#½pattern spaceŽWoutputX|sedê. €×Å#½Ïޕ

¼Ý3pattern space…:Õp.ÏޕŒ !§êbËÍÏޕ ŒÏë•ãyp^®àà#Îpattern space XÕoutput:×Í»(' Œ¼Ý) cyril@gyoza:~$ cat command.txt This describes the Linux ls command. This describes the Linux cp command. cyril@gyoza:~$ cat command.sed /Linux/{ h s/.* Linux \(.*\) .*/\1:/ p x }

uŒ`Äò·®

CHAPTER 4. SED

úƒ

4.4. SED COMMAND

43

cyril@gyoza:~$ sed -f command.sed command.txt ls: This describes the Linux ls command. cp: This describes the Linux cp command.

Tï¶Wו

cyril@gyoza:~$ sed ’/Linux/{h;s/.* Linux \(.*\) .*/\1:/;p;x;}’ command.txt

9\:Ï×Íh.Ïו. hold spaceÄBœpattern space1b æÍÏ ×•Ý­Q¡‚ð*ŽWls:¨3pattern space©bls: Q¡pŒls:t ¡.hold space«ls:øðX|t¡pattern space/ µÎæÍ݋—sed WoutputXŒcpÎ!øݼ§ X|^%‚©ÎËÍ¿:ÕÝspace3£\ð¼ðœ./39Ë Í 2]33copy/pasteµ?ÝAŒ!viÝßTŒœ|›º 4.4.3

 ×M

9• §]º 3æÍÝh, H, g, G, x…«K©bEŽ×• §AŒpattern matchŠ¬• `µRDŒ„ì«Ýúƒà¼ §Ë•|îÝpattern matchCpattern space, hold spaceÝ § • n .pattern space‹—XŒ\áìוX|ìוŽWpattern space ݋— • N \áìו«êGpattern spaceÝ ‹—=R¼Ž×•¬Î…«b Íembeddedð•Ðr|à \n¼îBœ©b9`|à\n¼ î • D „*ÕÏ×embedded newlineI N)à‰ AŒD3t9ìÆ •ÝJpattern space‹—1ºì¼ ]ºÕscriptcм×g • P printÕbembedded newlineÝו1ºXbpattern space‹— A ŒP3t9ìƕÝJpattern space‹—1ºì¼ ]ºÕscriptc м×g Join˕ /join/ { N s/\n/ /g }

.9•è畄*Wוèç uŒ`Äò·®

úƒ

4.4. SED COMMAND

CHAPTER 4. SED

/^$/ { N /^\n$/D }

š:0Õè畡.ìו ¼AŒ©bוèçèç• ì× •¿Wו1º3pattern spaceÄ9`ìÍúƒ /^\n$/D^®àpattern spaceIXŒ AŒb˕èçX|Delete*Ïוèçyìוèç 1ºì¼ 9`. Dú¨b®àÝX|¬XŒpattern space݋— µ /^$/×àºbוè畺ì¼9\DPKb]ºÝ®à |J¼ ®¥Ý § flow control branch

9Î༻ÉúƒÆ•Ýµ Îc…Ýif else, while9°×úƒ 9Š¤g:×R àã:'×ÍlabelQ¡àb label®Õ9Í2]ƕ • : label, 'label • b label branch ðÕlabel2]ƕAŒ^blabelµ;;ƕ à#® Õscript O • t label AŒ×͂ðWtest ?ŽfWñ¡®Õlabel X|Ä6 s///úƒ×Ràsúƒ×3túƒG 91A:» $ cat join.txt join second line C

3 +ŽDEa‚C™Ý; \ 9ו«îוÎ=3×sÝ $ sed ’{ :a N s/\\\n// t a}’ join.txt join second line C

3 +ŽDEa‚C™Ý; 9ו«îוÎ=3×sÝ 9j § • r \jn ÞjnappendÕêGpattern space • w ¶jn Þpattern space݋—¶ŒÕ×Íjn uŒ`Äò·®

CHAPTER 4. SED $ cat insert.sed //i\ 100 Gyoza Blvd\ San Jose, CA

Ïו Ïޕ œ9• t¡×•

$ cat lines first line second line multiple line line last line

Ïו

$ sed ’/first/r insert.sed’ lines first line //i\ 100 Gyoza Blvd\ San Jose, CA second line multiple line line last lin

Ïޕ œ9• t¡×•

Ïו Ïޕ œ9• t¡×•

$ sed ’/first/w firstline.txt’ lines first line second line multiple line line last line

Ïו

$ cat firstline.txt first line

̀

Œ•r • q Òsed • =

Ïו Ïޕ œ9• t¡×•

$ cat lines first line second line multiple line line last line $ sed -e ’/first/=’ -e ’/second/q’ lines 1 first line second line

Ïו Ïޕ uŒ`Äò·®

úƒ

4.4. SED COMMAND

45

úƒ

4.4. SED COMMAND

CHAPTER 4. SED

bœ9Ý»š:http://www.student.northpark.edu/pemente/sed/sedfaq.html

uŒ`Äò·®

Chapter 5

awk 5.1

+

ÝÌFÎawkfsed?àÝ2]8Eysed×•×•Ý §awkèºÝ × •/Iû›tŠÝ §b?powerfulÝ CP+°]º× § ;P |Î field

awk ’script’ var=value files awk -f scriptfile var=value files

ÍvarΊÝawkŽóvalueΛÝÂ9|༫shellŽóÚ; ¨² sedÝregular expressKJו•¼®/Ýíá†fE9øœ^ b ÄPawk.&àawkÝ×͎ó¼®regular expressÝíáfE.h û ›ô |DêÝJ¼fExŠÎàfEÕÐ ¼«×Íregular expressfE var ~ /re/ var !~ /re/

9øµœ]-Ý‚v9fEô!øºF/true, false| W×Ícondition tÝû› §|²awkb?9?àÝfunction|ñ§¨²ôbÝif,while, forŠfunctionÝæ9°fsed«shell)¿ÝæêîÝ&9ôÎÞ ¼ perlÝÃ͐ÝÁ 5.2

script

Á

×Íscriptã condition{procedure},condition{procedure},.....àW «sedœ 0Õ%‚f(patternI )†%‚›®(procedureI ) b×°/IÝ Žó|Q&Æ'×°fcondition|Îpattern regular expressTØ ÍÐ)f9͚:ìºÕÐrfEÕÐ ÍbËÍ¥Š Ý/ 47

5.3.

Žóû› §

CHAPTER 5. AWK

condition, BEGIN«END×Íscript;ðÎ9ø BEGIN {xxx} /re/{xxx} END{xxx}

׶P׊binit;װµ ßbŒßO`^âC×ø P”@ôŠb §Ÿ¡Ýroutine¼ §awk® ×ÍPlVÝscript+ Ž èºÝ×ÍgeneralÝ”@Ý § ÕÕb¿Íèç• $ awk ’BEGIN{x=0} /^$/{x++} END{print x}’ scripts.tex

×'x=0¡BEGIN¡Ýµ3ƕQ¡N\ו ¼AŒÎèç •µ x++t¡\Õj Œx ŠBœ3î«Ý»…awkݎó«cÎ×øÝôµÎ^bþÐrÝ9 \«shell perl‡scriptf´×ø 5.3

Ž ó û › §

…«œ¥ŠÝËÍL • record µÎווݣ] • field ;ðãspaceTïtab"âÝ£]ûµÎfield š:»¬¥Œshell command lineݎSrÔSr awk

$ cat /etc/mnttab /proc /proc proc fd /dev/fd fd mnttab /etc/mnttab swap /var/run swap /tmp tmpfs

dev=31c0000 1022606134 rw,suid,dev=32c0000 1022606198 mntfs dev=3380000 1022606209 tmpfs dev=1 1022606209 dev=2 1022606211

$ awk ’/swap/{print $2}’ /etc/mnttab /var/run /tmp $ awk Hello Hello Hello Hello Hello

’{print "Hello World"}’ /etc/mnttab World World World World World

×Þû› ÎtabÞëû› Îèç uŒ`Äò·®

CHAPTER 5. AWK

5.3.

$ cat datafile 99 98 3.5 300 298 4.9 498 493 5.9 699 698 7.6 900 748 9.0 1200 703 9.6 1500 651 10.4 1698 627 10.8

Bœ 9øÎ

ËÍû›íŒ

×Íû›

input output $ awk ’{print $1 $2}’ datafile 9998 300298 498493 699698 900748 1200703 1500651 1698627

9øÎinputËÍû›íŒoutputËÍû› àprintíŒû›ã
9øÎinputËÍû›íŒoutput×Íû› $ awk ’{print $1 "," $2}’ datafile 99,98 300,298 498,493 699,698 900,748 1200,703 1500,651 1698,627

ôµÎ1print $1$2 ‡yprint $1 $2 uŒ`Äò·®

Ž ó û › §

49

5.3.

Žóû› §

5.3.1

CHAPTER 5. AWK

/Žó

tÝ C+°ÝŠŽóx,y,z....awkb×°/ݎó( û›îÝ/ Žó ARGC ARGV ARGIND $0 $1....$n

: : : : :

ENVIRON ERRNO

: :

number of arguments on command line array containing the command line arguments

J•record ÏnÍû›(field) ×Íassociate arrayâbIݕ(Žó t¡systemŒýÝerror numberš:/usr/include/errno.h

FILENAME : FIELDWIDTHS :

current filename list of field widths

FS OFS RS ORS NF NR

field separator tab output field seperator record separator newline output record seperator newline number of field number of record

: : : : : :

/ÎèçT /Îèç /Î /Î

ÍFS, OFS, RS, ORS, NF, NRÎðàÕݚ:» $ cat /etc/passwd list:x:38:38:SmartList:/var/list:/bin/sh irc:x:39:39:ircd:/var:/bin/sh nobody:x:65534:65534:nobody:/home:/bin/sh cyril:x:1000:1000:Cyril Huang,,,:/home/cyril:/bin/bash $ awk ’{FS=":"; print $7}’ /etc/passwd /bin/sh /bin/sh /bin/sh /bin/bash $ awk ’{FS=":"; OFS=","; print $1,$6,$7}’ /etc/passwd list,/var/list,/bin/sh irc,/var,/bin/sh nobody,/home,/bin/sh cyril,/home/cyril,/bin/bash

uŒ`Äò·®

CHAPTER 5. AWK

Ð~

5.3.

Ž ó û › §

51

|J¼®conditionà ô|J¼®conditionà¤gŽóregular express matchÕ

NF NR $1 $2....

$ cat datafile # This is the data file from experiment 99 98 3.5 300 298 4.9 498 493 5.9 # Failed data 122 123 699 698 7.6 900 748 9.0 1200 703 9.6 1500 651 10.4 1698 627 10.8 $ awk ’NF == 3 && $1 ~ /[0-9]+/{print $3,$1,$2}’ datafile 3.5 99 98 4.9 300 298 5.9 498 493 7.6 699 698 9.0 900 748 9.6 1200 703 10.4 1500 651 10.8 1698 627

5.3.2

awk

ŽóshellŽó

awk  sedKÎQÃshell programmingÝ? Ì.hŠ«shellŽóÚ; ; PÝ var=valuevarµÎawkŽóvalueµÎshellŽóÝÂ

# fs_mounted $dev $mnt_pt $fs_type # This is shell script version of fs_mounted, check if the file system is # mounted. fs_mounted() { _BINGO= [ $# -eq 3 ] || return $ERRNO_EINVAL _BINGO="‘$AWK ’{if (\$1 == _DEVICE && \$2 == _MNT_PT && \$3 == _FS_TYPE) print \$1}’ _DEV [ "$_BINGO" ] || return -1 return 0; }

uŒ`Äò·®

5.3.

Žóû› §

CHAPTER 5. AWK

shell scriptÝƕshell commandÝawkEy×°1ºC- §«sed×ø Š TF 9Í»…«¥Œ$1 $2 $33AWK ’ ’ŽSr…«ÝÎawkÝ$1$2$3 3 ²« DEVICE=$1...ÎshellÝ $1 $2 $3 DEVICE MNT PT ‡ÎawkÝ Ž óX|awkÝ$1 $2 $3b\9Íescape3G«ôµÎ1shell  §¸Æ¬. 9°X›awk §

5.3.3

pArraysplitÐó

XbawkÝarrayKÎassociate array,ôµÎhashôµÎñb(CidÝp 9Í(CidµÎhashÝkey×&Æà1, 2 ,3 ...¼ ®pÝidÛý3 awk…«.&&Æà(̼ id index¼¨´pÄawkœÏ€AŒ:Õ Îó ClÝindexô| 3C…«àÝ×ø ¥Œ!parray[1]Îarray[0]«c×ø &Ɲ|¼ x[1], x[2]...Ýpï1,2,3 ...45 ¬associate arrayÝ4Î& Ɲ|×Ý¥Œassociate arrayÝ¥ýŠà SrÀR¼š:for loopÝà ° |àsplit(string, array, [sep])¼ÿÕ×Ípsep^b›µàFSÝ † 9ÍstringÝû›5â×Íû›µÎ×Íp-ô $ cat split.awk #! /bin/awk BEGIN{FS=":"} /cyril/{ print $0 split($0, afield) for (i = 0; i < NF; ++i) { print i","afield[i] } delete afield[2] for (i = 0; i <= NF; ++i) { print i","afield[i] } } $ awk -f split.awk /etc/passwd lcyril:x:100:1::/export/lcyril:/usr/bin/bash 0, 1,lcyril 2,x 3,100 4,1 5,

uŒ`Äò·®

CHAPTER 5. AWK

5.4.

ÃÍ×+°

53

6,/export/lcyril 7,/usr/bin/bash 0, 1,lcyril 2, 3,100 4,1 5, 6,/export/lcyril 7,/usr/bin/bash

ÃÍ×+°

5.4

tÝû›ÝŽó©à°²awkfsedúÝ3y?#P+ŽÝ×] ° awkÝ+°œ c1@3awkˍŽÝbcÝÁœ|µºÝ Q ô|. awk.c 5.4.1 C

ó.ìÕÐ

Ý×ó.

9Îfortranݼó)

+ - * / % ++ -- ^ **( C

Ý×¼ = += -= *= /= %= ^= **=

C

Ýאì Ý

! == < > <= >= != && || ?: (c cond ? result1 : result2

AŒcondWñ/result1Q/result2)

ݐìÕЅ«bÍf´©½ÝµÎpattern matchÕÐ ~, !~  Þ ¼ œbàÝv«ÕÐ~=xŠÎregular express;ðmatchÝΠו•®

/ÝfEAŒŠEØÍ©Žó†re match`µŠàÕ9ÍÕ Ð AŒxÎÍZ°óC condition perl

if (x ~ /^[0-9]+/) { x += y }

uŒ`Äò·®

5.4.

ÃÍ×+°

5.4.2

CHAPTER 5. AWK

if

^%‚ÝRµÎc‚ if (condition) { } else if (condition) { } else { }

¥Œelse if«c+°×ø 5.4.3

for loop

9\ÝforbËÍÎcbourne shellÝá)perlôÎ×øÄperlàÝ c shellÝ+° for (i = 0; i < 10; i++) { } for x in xarray { }

š:» $ cat gyoza.awk #! /bin/awk heehee BEGIN { x[1]="I" x[2]="am" x[3]="a" x[4]="gyoza" y["I"]="I" y["am"]="am" y["a"]="a" y["gyoza"]="gyoza" for (i = 1; i < 5; i++) { print x[i] } for item in x { print item, x[item] } for item in y { print item, y[item] } }

uŒ`Äò·®

CHAPTER 5. AWK

¡«Ý

5.5. FUNCTION 55

^bঠ&©Îþ9ÍBEGIN‚

gyoza.awk $ awk -f gyoza.awk gyoza.awk I am a gyoza 2 am 3 a 4 gyoza 1 I gyoza gyoza am am I I a a

5.4.4

while

^%‚ÝRµÎc‚ while (condition) { statment } do { statment } while (condition) for loopwhile loopK«c×ø|àbreakÒcontinue†9loopðÕì Í loop

5.5

function

«cH×øÝ9Î×Ëscriptà#‚typeŠ…×ô^b%‚ pass by value, pass by addressŽóÎglobalÝ # ;P function fun(arg1, arg2) { arg1 = arg2 xxxx }

4Ý»

$ cat sort.awk

uŒ`Äò·®

5.6.

̀Ðó

CHAPTER 5. AWK

# sorting function function sort(Array, elements, temp, i,j) for (i = 2; i<= elements; ++i) { for(j = i; array[j - 1] > array[j]; --j) { temp = array[j] array[j] = array[j - 1] array[j - 1] = temp } } return } # main routine, { for (i = 2; i <= NF; ++i) { grades[i - 1] = $i } sort(grades, NF-1) printf("%s: ", $1) for (j = 1; j <= NF - 1; ++j) { printf("%d ", grades[j]) } printf("\n") }

וו¼

—— YY

$ cat grade.txt 100 60 75 23 100 98 99 89

—— YY

$ awk -f sort.awk grade.txt : 23 60 75 100 : 89 98 99 100

̀Ðó

5.6 5.6.1

C™ §-match‚ð

C™î § sedbs///9˂ðÿàî×°/˜Ðó • F/Ð)regexÝ3stringݛH match(string, regex)



F/C™: F/3ÏmÍC-?¡ónÍC-ÝC™n^›µÕ9 substr(string, m, [,n])

‚ð: ‚ðÝ¿ÍÐóbÝF/œ©½ uŒ`Äò·®

CHAPTER 5. AWK • •

.

…«Ð)

5.6.

̀Ðó

57

ÝÏ×ÍC™ðWstring1WF/1

string2 regex sub(regex, string1, string2)

.string2…«Ð)regexÝC™globallyÝI‚ðWstring1 ‡ysedÝs///g F/Jóî‚ðóê gsub(regex, string1, string2)



F/×ÍC™ string2…«Ð)regexÝÏnÍC™ðWstring1 ‡ysedÝs///nth match ¬Îstring2^b;Ž gensub(regex, string1, nth match, string2)

^›;;Î$0nth match|àgTGîglobally(I)š:»

string2

$ cat match.awk #! /bin/awk BEGIN{FS=":"} /cyril/{ print $0 print match($0, /cyril/) print substr($0, match($0, /cyril/), length("cyril")) print gensub(/cyril/, "mark", 2) print $0 sub(/^.*cyril/, "mark") print $0 } $ awk -f match.awk /etc/passwd lcyril:x:100:1::/export/lcyril:/usr/bin/bash 2 cyril lcyril:x:100:1::/export/lmark:/usr/bin/bash lcyril:x:100:1::/export/lcyril:/usr/bin/bash mark:/usr/bin/bash

9Í»àÝlength()9ÍÐóregexàSrbstringÝ2]Šà double quoteÀR¼àgensubº;Žstring2Ý ‚vš:ÏëÍprint $09\ ÎbgreedyÝ[T3X|©yì¡«×^ 5.6.2

íáíŒ §print(f )

íŒî¼1print̍ŽÝà°Äb??Ýformat팵 c…Ýprintf Tïfortran×ø printf()

à°«cÐó×ø

{printf("The sum on line %s is %d.\n", NR, $1+$2)}

uŒ`Äò·®

5.6.

̀Ðó %s %d %n.mf

CHAPTER 5. AWK

î×ÍC™ î×ÍJó î×ÍnÍJómÍóݘFó

Bórand()

5.6.3

®ß+y0 Õ 1 ÝBó BEGIN { srand(systime()) random_num = rand() print random_num }

F/1970, 1, 1Õ¨3ÝJó srand()®ß×ÍÌaÝBóp|º ¸à

systime() rand()

5.6.4

Ùsystem()

9͜ UnixÝsystem()9ÍÐó BEGIN {if (system("ls -l")) != 0) { print "command failed" } }

Í€Ý ó.Ð󇇵|+ÛÝ

uŒ`Äò·®

Chapter 6

perl 8Eysed, awk, shell script‡ Ì Larry WallÆÿŠs€×˝|㠂 ×°ÓÚÓâscript½;àlÝscript ÌfRXbÝscriptŠpower §Rregular expressô?]-ŠXÝ×°AgreedyÝ®Þperlt¡« system callÝ=”jn,processsocket program‡Ý §¯€ŽWœúÝ script+Ž perl«Í€Ñshell, TCL/expect...‡script+ŽÍ@ÎàC¶Œ¼Ý N ×ËscriptÍ@KÎ×ÍƕP©Ä9ÍƕPUÿ×°/+° ºœŠÕ9°!JQ¡»ð9°scriptŽó×]º‡‡ŽWŠ ÝcŽó« ]º  Q¦!Í@t¡ÎKÎassemblyݎó«]º¼Æ•µ«shell, awk× ø

6.1

6.1.1

ÃÍ+°£]lV Žó

Ñ'ãÂKŠÍþÐr 59

6.2.

?POWERÝREGULAR EXPRESSION

6.1.2

6.2 6.3 6.4 6.4.1

f×

?powerÝregular expression ðàÐó Ù § process

6.4.2

jn

6.4.3

system call

6.5

module

uŒ`Äò·®

CHAPTER 6. PERL

Chapter 7

Bourne shell, perl

´

 C+ ° f

9ÍÍ@Î&OSÝb`BœàÝC, shell perlÎ&ðàÕÝ Ì ¨3E93Ë Ì+°†Íf´ 7.1

Žó

LŽó shell var= perl $var =

C int var = char var = Makefile var = var :=

¸àŽó shell $var ${var} awk var

61

7.2.

pHASH

 +°f´

CHAPTER 7. BOURNE SHELL, PERL C

perl $var C var Makefile ${var} or $(var)

Š¥ŒÝÎ • shellÝL$ ¬Šá¼ŽóÂ`׊$ perlµf´×l ÑA¢ µÎ$Ðr CµÎK • shell݇rG¡bèç var= var = Î×øÝ perlCµ^b§×MakefileÎL¸à «shell ×ø¬Î‡rG¡|bèçX|b°Ëš4B×ì 7.2

pHash

shell array="e1 e2 e3" perl @array = {e1, e2 ,e2}; %hash = {key1 => val1, key2 => val2, key3 => val3}; C int array[] = {1, 2, 3}; shell

ݙl£]§list…«-ôàspace5tðàݝ)

for var in $array do cmd1 done array

Ý-ôµÎàspace5Ý£] perlb͜ Ýforeach

foreach $var (@array) { xxx }

Í@9ÎC shellݶ° C^b 9ø×Í×͊›;arrayÝ-ô›ŽóÝ^ × uŒ`Äò·®

 +°f´

CHAPTER 7. BOURNE SHELL, PERL C

7.3

fB–

7.3.

fB–

63

shell if test; then dosomething elif test; then doother else allright fi perl if (c) { do_something; } elsif () { do_other; } else { allright; } C if (c) { do_something; } else if () { do_other; } else { allright; }

9\Š¥ŒÝÎshellmŠÀrelse ifݶ°ëÍ×øfP¶° shell^b׊à()‘œfP©ŠtestÎØ͝ƕÝB–µ? 7.3.1

ff´

shell

C™ [ "str1" = "str2" ] ó [ num1 -ne num2 ] perl

C™ if ($str1 ne $str2) ó if ($num1 == $num2)

uŒ`Äò·®

7.4.

]º×

 +°f´

CHAPTER 7. BOURNE SHELL, PERL C

C

C™ if (strcmp(str1, str2)) ó if (num1 == num2)

Š¥ŒóÂf´C™f´C™ §ìf´ ã9\&Ɲ|:ŒÍ @perlÎ&ðbÄPúÝ 7.4 7.4.1

]º  × while



shell while test do cmd done perl

«cÎ×øÝtݎóà°×ø

while (condition) { statment1; } unless (condition) { statment1; } C while (condition) { statment1; } do { statment1; } while (condition)

7.4.2

for loop

Ý Î C…Ýfor loop

Bourne shell for

for var in "element1 element2 element3..." do echo $var done

uŒ`Äò·®

 +°f´

CHAPTER 7. BOURNE SHELL, PERL C perl

bËËforÝà°

for ($i = 0; $i < 10; $i++) { statement } foreach $var (@array) { statement; } C

Ýà°

for (i = 0, init = 1; i < 10; i++) { statement; }

7.5

—P

shell func1() { arg1=$1 arg2=$2 } awk function func1(arg1, arg2) { xxx } perl sub func1(arg1, arg2) { xxx } C int func1(int arg1, char *arg2) { xxx }

uŒ`Äò·®

7.5.

—P

65

7.6.

7.6

ۊ

ۊ

shell # comment perl # comment C /* comment */

uŒ`Äò·®

 +°f´

CHAPTER 7. BOURNE SHELL, PERL C

Bibliography [1] Linux In a Nutshell, Ellen Siever, O’Reilly & Associates, ISBN 0596000251 [2] Sek & Awk, Dale Dougherty, et al, O’Reilly & Associates, ISBN 1565922255 [3] Perl Cookbook, Tom Christiansen, Nathan Torkington O’Reilly & Associate, ISBN 1565922433 [4] The C Programming Language, Brian W. Kernighan, Dennis M. Ritchie, Prentice Hall, ISBN 0131103628

67

Related Documents

Scripts
November 2019 27
Scripts
June 2020 14
Scripts
October 2019 32
Scripts
November 2019 27
Scripts
June 2020 14
Scripts Dba
November 2019 23