sed无法往空白文件中插入内容的解决办法

sed 是一个强大的文本文件处理程序,但是因为它是基于流来工作的,所以导致它无法对一个空文件进行操作。

Sed is a stream  editor. 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 the  input(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

上面这段代码就相当与其它编程语言中的三元运算符( ?: )

我来评几句
登录后评论

已发表评论数()

相关站点

+订阅
热门文章