Shell程式設計實踐3

2021-10-11 02:29:24 字數 1794 閱讀 4201

實驗目的

(1)熟悉shell指令碼語法。

(2)掌握sed, grep 和awk操作。

一.使用sed操作,文字如下:

123abc456

456def123

567abc789

789def567

要求輸出:

456abc123

123def456

789abc567

567def789

**如下:

sed -r -e 's/([1-9]*)([a-z]\*)([1-9]\*)/\3\2\1/'

-e 's/[a-z]/\u&/g' filename

二.使用sed操作任意文字:

刪除檔案每行的第乙個字元

sed 's/^.//' filename
刪除檔案每行的第二個字元

sed 's/.//2' filename
刪除檔案每行的最後乙個字元

sed 's/.$//' filename
刪除檔案每行的倒數第二個字元

sed -r 's/.(.)\$/\1/' filename
刪除檔案每行的第二個單詞

sed -r 's/^([a-z]+[\^a-z])+)[a-z]+/\1/' filename
刪除檔案每行的倒數第二個單詞

sed -r 's/[a-z]+([\^a-z]+[a-z]+)\$/\1/' filename
刪除乙個檔案中所有的數字

sed 's/[0-9]//g' filename
三.對於pets檔案做sed操作

文字如下

this is my cat

my cat

's name is betty

this is your dog

my dog's name is frank

this is my fish

my fish's name is george

this is my goat

my goat's name is adam

輸出pets. txt的第2-3行內容

sed -n '2,3p' filename
過濾出含有fish字串的行

sed -n '/fish/p' filename
刪除含有dog字串的行

sed '/dog/d' filename
將檔案中的my字串全部替換為your

sed 's/my/your/g' filename
四.進行grep操作

grep查詢包含dog的行

grep 『dog' filename
grep查詢不包含dog的行

grep -v 'dog' filename
grep查詢dog或者fish開頭的行

grep '^fish' filename |grep '\^dog'

shell程式設計 3

要定義乙個shell函式,我們只需要簡單地寫出它的名字,然後是一對空括號,再把有關的語句放在一對花括號中,如下所示 function name statements 實驗 簡單的函式 bin bash foo echo function foo is executing echo script st...

shell程式設計高階3

二 case結構條件句 1 語法格式 case 字串變數 in 值1 指令1 值2 值3 值4 指令2 指令 esac 2 示例 1 示例1 根據使用者的選擇輸入,判斷是哪種水果並加上不同顏色 a 給字串加顏色 vi services scripts echo color01.sh echo e 0...

shell程式設計100例(3)

11 石頭 剪刀 布遊戲 bin bash game 石頭 剪刀 布 num katex parse error expected eof got at position 12 random 3 生成0到2的乙個隨機數 com echo 請根據下列提示選擇您的出拳手勢 echo 1.石頭 echo ...