sed: extra characters at the end of l command及undefined label錯誤

sed: extra characters at the end of l command及undefined label錯誤

前言

筆者在MacOS下使用sed -i時出現了extra characters at the end of l command的錯誤,經過查詢,才知道sed -i在Linux和MacOS上的用法不完全一樣。

問題描述

使用以下指令替換test.txt中的字串:

echo hello > test.txt
sed -i 's/hello/good bye/' test.txt

這時會出現以下錯誤:

sed: 1: “test.txt”: undefined label ‘est.txt’

嘗試改用完整路徑:

sed -i 's/hello/good bye/' `pwd`/test.txt

這時就出現了extra characters at the end of l command的錯誤:

sed: 1: “/Users/lorenzo/test.txt”: extra characters at the end of l command

發生原因

筆者上網查詢這個錯誤發生的原因,發現是sed -i在Linux及MacOS下的用法不同所致。
sed -i這個指令會in-place(原地)修改檔案,它在兩種作業系統下都可以接受參數。
因為sed -i是原地修改檔案,通常我們會希望為原來的檔案做備份。而sed -i所接受的參數就表示該備份檔案的副檔名。

我們可以使用man sed這個指令來查看sed這個指令在兩種不同作業系統下的用法:

  • man sed in Linux

    -i[SUFFIX], --in-place[=SUFFIX]
    edit files in place (makes backup if SUFFIX supplied)

  • man sed in MacOS

    -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 cor-
    ruption or partial content in situations where disk space is exhausted, etc.

我們可以看到,sed -i後面的參數在Linux下是可選的,而在MacOS下卻是必須的。

解決辦法

上述兩個問題都可以用同一個辦法解決,那就是正確地使用sed -i
在MacOS下,我們必須傳入參數。我們可以:

使用bak的副檔名備份原始檔案。

sed -i '.bak' 's/hello/good bye/' test.txt

或選擇不備份:

sed -i '' 's/hello/good bye/' test.txt

我們可以使用以下指令來查看結果:

cat test.txt #good bye

我們可以看到,test.txt裡的內容己被成功替換。

另外,如果有做備份,可以使用以下指令來查看備份檔的內容:

cat test.txt.bak #hello

參考連結

sed command hits “undefined label” error on Mac OS X
OS X + Sed: “extra characters at the end of l command” Error

猜你喜欢

转载自blog.csdn.net/keineahnung2345/article/details/84337927
end
sed