sed無法往空白檔案中插入內容的解決辦法
sed 是一個強大的文字檔案處理程式,但是因為它是基於流來工作的,所以導致它無法對一個空檔案進行操作。
Sed is a streameditor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline).While in some ways similar to an editor which permits scripted edits (such as ed), sed works by making only one pass over theinput(s), and is consequently more efficient.But it is sed’s ability to filter text in a pipeline which particularly distin-guishes it from other types of editors.
有時候你需要往一個可能為空的檔案中寫入內容,這個時候怎麼辦呢?我想到的辦法是判斷檔案是否為空,如果為空的話,則用echo 來往檔案中寫入內容:
if test -s file.txt; then sed -i '$a\test content' file.txt else echo 'test content' >> file.txt fi
當file.txt檔案為空檔案時,就會使用echo往檔案中追加內容了。不過這個寫法有點繁瑣,有沒有更簡潔的寫法呢?當然有:
test -s file.txt && sed -i '$a\test content' file.txt || echo 'test content' >> file.txt
上面這段程式碼就相當與其它程式語言中的三元運算子(?:
)