2012-11-10 23 views
11
echo -n 'I hate cats' > cats.txt 
sed -i '' 's/hate/love/' cats.txt 

這會正確更改文件中的單詞,但也會在文件末尾添加換行符。爲什麼?這隻發生在OSX中,而不是Ubuntu等。我怎樣才能阻止它?爲什麼sed在OSX中添加新行?

+0

不會發生在10.6上。可能只是你的版本。 –

+2

這發生在10.6.8和10.7.3。嗯。 –

+0

你的編輯會顯着改變事物。我在下面回答。 –

回答

7
echo -n 'I hate cats' > cats.txt 

該命令將使用單引號之間的11個字符填充'cats.txt'的內容。如果你在這個階段檢查cats.txt的大小,它應該是11個字節。

sed -i '' 's/hate/love/' cats.txt 

該命令將讀取該文件cats.txt 一行一行,並與其中每行有過的「恨」的「愛」換成了一審文件替換它(如果這樣一個實例存在)。重要的部分是理解一條線是什麼。從sed的手冊頁:

Normally, sed cyclically copies a line of input, not including its 
terminating newline character, into a pattern space, (unless there is 
something left after a ``D'' function), applies all of the commands 
with addresses that select that pattern space, copies the pattern 
space to the standard output, appending a newline, and deletes the 
pattern space. 

注意appending a newline部分。在你的系統中,即使沒有終止的換行符,sed仍然將你的文件解釋爲包含單行。所以輸出將是11個字符,加上附加的換行符。在其他平臺上,情況並非一定如此。有時sed會完全跳過文件中的最後一行(有效刪除它),因爲it is not really a line!但在你的情況下,sed基本上是爲你修復文件(作爲一個沒有行的文件,它是輸入到sed的輸入)。

看到更多細節在這裏:Why should text files end with a newline?

的一種替代方法,您的問題見這個問題:SED adds new line at the end

0

你可以做的另一件事情是這樣的:

echo -n 'I hate cats' > cats.txt 
SAFE=$(cat cats.txt; echo x) 
SAFE=$(printf "$SAFE" | sed -e 's/hate/love/') 
SAFE=${SAFE%x} 

如果貓的方式。 txt以換行符結束,並保存。如果沒有,它不會添加一個。

0

這對我有效。我不必使用中間文件。

OUTPUT=$(echo 'I hate cats' | sed 's/hate/love/') 
echo -n "$OUTPUT" 
+0

你的第一個'echo'沒有'-n'。 –

0

請注意,GNU sed不會在Mac OS上添加換行符。

+0

我剛剛安裝了gsed(GNU sed)4.4,並添加了一個換行符。嘗試一下:'brew install gnu-sed' –

+0

$ gsed --version gsed(GNU sed)4.4 $ gsed -i''s/hate/love /'cats.txt $ xxd cats.txt 00000000 :4920 6c6f 7665 2063 6174 73我喜歡貓 –

0

避免此問題的一個好方法是使用perl而不是sed。 Perl會尊重原始文件中的EOF換行符,或缺少它。

echo -n 'I hate cats' > cats.txt 
perl -pi -e 's/hate/love/' cats.txt 
相關問題