iT邦幫忙

0

shell script 的設計探討

Shell script

Shell script(外殼腳本)
為一種直譯語言,都由terminal直接呼叫.sh檔案,不像C或Java需要經過編譯生成.class或是.exe檔,直接開啟終端機到該資料夾路徑./***.sh即可執行

https://ithelp.ithome.com.tw/upload/images/20211204/20137810lQev5pIX2n.jpg

#! /bin/bash - 聲明該腳本由什麼解釋? 

井字號驚嘆號#!放在一起就標誌這是一個ShellScript,而後面就是標示編譯它的路徑,還有/bin/csh , /bin/perl , /bin/awk , /bin/sed , /bin/echo其他腳本
readonly - 宣告變數只可讀取不可再被更改
typeset - 用來分配引數$1交由 echo秀出資料
引數 - $0代表名字 $1~$n 由terminal傳入 含式內只能傳$1

	Exit與return的區別

作用不同,exit用於在程式運行的過程中隨時結束程序,exit的參數返回給OS的。Exit式結束一個進程,它將刪除進程的內存空間,同時把錯誤訊息返回父進程,而return式返回和數值並退出函數
通常都可以用 echo$?
呼叫出返回參數,成功為0,若不成功則有相對應的status codes

 	Return 關鍵字

用於結束函數並返回一個結果。若return不帶參數時,則返回函數體中最後一個命令的返回值,一樣可由echo $?呼叫出

現在大概有概念了,shell script也可以直接使用一些linux指令
例如 pwd ls 等等

如果我現在想設計一個.sh檔案
可以讓我外部傳入一個引數1為檔案路徑
並且搜尋該路徑找出引數2位於檔案列數
最後echo "The search keyword:$1 is in file $2 line."

該怎麼做呢?

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

4
一級屠豬士
iT邦大師 1 級 ‧ 2021-12-04 15:43:04
最佳解答
grep -rnw '/path/to/somewhere/' -e 'pattern'

https://ithelp.ithome.com.tw/upload/images/20211204/20050647AQgkKYtFPZ.png

看更多先前的回應...收起先前的回應...

沒有echo "The search keyword:$1 is in file $2 line."
因為結果會是
The search keyword:~/study2021/s2112/d1205 is in file 南 line.
/images/emoticon/emoticon06.gif

哇~~~ 太感謝了 shell 指令大神><

https://ithelp.ithome.com.tw/upload/images/20211204/20137810wI5JjbOWAv.jpg

不好意思,我照了您的指令去嘗試
他讀不到記事本中的字,我檢查了指令好像也沒錯
請問有什麼問題嗎?

我查看了一下好像是 git bash 不支援grep語法嗎?

https://ithelp.ithome.com.tw/upload/images/20211204/20137810fjsVzczEXD.jpg
原來要用grep-n
現在好了,會顯示出列與行了
該怎麼將檔案名為$1 與 列數 $2
成為一個迴圈
跑成
The search keyword:S is in file 2 line.
The search keyword:S is in file 5 line.
呢?
看有沒有人寫得出來 應該不難

Winter iT邦新手 5 級 ‧ 2021-12-05 06:40:18 檢舉

grep -n 'S' test.txt |awk '{printf "The Search keyword:S is in file %d line\n",$1}'

我要發表回答

立即登入回答