Shell-Script
如何使用 if 語句檢查一行中的字元串?
我期待輸出如下
$ ./test.sh Manifest.txt test/directory1/dir2/Main test/directory1/dir2/Main contains Main test/directory1/dir2/Main have string Main directory2/dir3 directory2/dir3 dont have string Main
我正在使用如下腳本
#!/usr/bin/ksh while IFS='' read -r line || [[ -n "$line" ]]; do for project in $line do echo $project if [[ "$project" =~ ^(Main)$ ]]; then echo "$project contain Main" exit 1 else echo "$project dont have Main" fi done done < "$1"
但這並沒有返回預期的輸出。
輸出為
test/directory1/dir2/Main test/directory1/dir2/Main dont have Main dir2/dir3 dir2/dir3 dont have Main
正則表達式
^(Main)$
將與$project
. 這似乎是一條路。問題是,除非$project
完全是Main
,否則比較將失敗。這是因為表達式錨定在字元串的開頭和結尾。我相信只需將表達式更改為即可
Main$
為您解決。這將Main
匹配$project
.