开发者

Opening a file in write mode

I have a file called a.txt. with values like

1
2
3
...

I want to overwrite this file but

echo "$var" >> a.txt
echo "$var1" >> a.txt
echo "$var2" >> a.txt
...

just appends. Using > is not useful as well. How can i overwrite with using >> operator in she开发者_Python百科ll script?


You may want to use > for the first redirection and >> for subsequent redirections:

echo "$var" > a.txt
echo "$var1" >> a.txt
echo "$var2" >> a.txt


> truncates the file if it exists, and would do what you originally asked.

>> appends to the file if it exists.

If you want to overwrite the content of a file (not truncate it), use 1<>

e.g.:

[23:58:27 0 ~/tmp] $ echo foobar >a
[23:58:28 0 ~/tmp] $ cat a
foobar
[23:58:50 0 ~/tmp] $ echo -n bar 1<>a
[23:58:53 0 ~/tmp] $ cat a
barbar


In what way is using > not useful? That explicitly does what you want by overwriting the file, so use > for the first and then >> to append future values.


echo "$var
$var1
$var2" > a.txt

or

echo -e "$var\n$var1\n$var2" > a.txt
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜