【學習 - shell - unix/mac的sed命令】

在jenkins構建時,使用在linux服務器驗證過的腳本,在mac執行機上一直報錯,查看是sed -r命令異常,報錯日誌:

++ sed -r 's/"//g'
sed: illegal option -- r
usage: sed script [-Ealn] [-i extension] [file ...]
       sed [-Ealn] [-i extension] [-e script] ... [-f script_file] ... [file ...]

查找資料才瞭解到,mac和unix用的是BSD的shell,linux用的是gun的shell,而這兩種在某些命令上存在些許差異,而這次的問題就是由於mac shell sed命令沒有-r參數(在linux shell中-r參數表示使用正則運算式作爲查找條件)
在mac查看相關sed解釋:man sed
針對本次截取目的:去掉字符串中的雙引號
linux shell sed:echo $build_moduleList | sed -r 's/"//g’
mac shell sed:echo $build_moduleList | sed 's/"//g’

在此也記錄下查詢到的其他sed差異:

1,sed -i
linux sed -i ‘s/old/new/g’ file
mac OS sed -i ‘’ ‘s/old/new/g’ file # 加空串是因爲這裏的sed強制要求備份

2,插入行
linux sed -i “/startline/a\$string” file # 行後追加
sed -i “/endline/i\$string” file # 行前插入
mac OS sed -i “” -e “/startline/a\
$string” file # 行後追加,需要加-e和換行
sed -i “”-e “/endline/i\
$string” file # 行前插入,需要加-e和換行

3,刪除行
a) 刪除匹配行中間的部分:
linux sed ‘/PATTERN-1/,/PATTERN-2/{//!d}’ file
mac OS sed ‘/PATTERN-1/,/PATTERN-2/{//!d;}’ file # 花括號前多加個分號,以避免 extra characters at the end of d command 錯誤

b) 刪除匹配行及中間的部分:
linux & mac OS sed ‘/PATTERN-1/,/PATTERN-2/d’ file

c) 刪除匹配行及之後的部分:
linux & mac OS sed ‘/PATTERN-1/,$d’ file

d) 刪除特定行號直接的部分(如2-4行):
linux & mac OS sed ‘2,4d’ file

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章