在linux系統(tǒng)上使用sed命令進行文件內(nèi)字符串替換是非常順暢的。例如,以下命令在linux上可以無縫工作:
sed -i "s/find/replace/g" file.txt
然而,在macos上使用相同的命令時,可能會遇到錯誤。這是因為macos和Linux在處理sed命令的-i選項上存在差異。具體來說,macOS使用的是BSD版本的sed,而Linux使用的是gnu版本的sed。
根據(jù)Stack overflow上的一篇帖子《sed command with -i option (in-place editing) works fine on ubuntu but not Mac》,我們了解到-i選項在兩者之間處理方式的細微差別。在macOS上,-i選項需要一個后綴參數(shù),即使你不希望創(chuàng)建備份文件,也必須提供一個空字符串作為后綴。例如:
sed -i "" "s/find/replace/g" file.txt
Linux版本的sed允許-i選項后跟一個可選的后綴,如果不提供后綴,則不會創(chuàng)建備份文件:
-i[SUFFIX], --in-place[=SUFFIX] edit files in place (makes backup if SUFFIX supplied)
而在macOS上,-i選項要求必須提供一個后綴:
-I extension Edit files in-place, saving backups with the specified extension. If a zero-length extension is given, no backup will be saved. It is not recommended to give a zero-length extension when in-place editing files, as you risk corruption or partial content in situ- ations where disk space is exhausted, etc. Note that in-place editing with -I still takes place in a single continuous line address space covering all files, although each file preserves its individuality instead of forming one output stream. The line counter is never reset between files, address ranges can span file boundaries, and the ``$'' address matches only the last line of the last file. (See Sed Addresses.) That can lead to unexpected results in many cases of in-place editing, where using -i is desired. -i extension Edit files in-place similarly to -I, but treat each file indepen- dently from other files. In particular, line numbers in each file start at 1, the ``$'' address matches the last line of the current file, and address ranges are limited to the current file. (See Sed Addresses.) The net result is as though each file were edited by a separate sed instance.
為了在Linux和macOS上都能正確使用sed -i選項,可以采用以下方法進行調(diào)整:
# 定義sed -i 參數(shù)(數(shù)組) # Default case for Linux sed, just use "-i" sedi=(-i) case "$(uname)" in # For macOS, use two parameters Darwin*) sedi=(-i "") esac ######## sed "${sedi[@]}" "s/find/replace/g" file.txt
如果你更喜歡使用GNU sed的語法,可以考慮在macOS上安裝gsed:
參考資料《sed command with -i option (in-place editing) works fine on Ubuntu but not Mac [duplicate]》
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載。
THE END