简体   繁体   English

如何在Unix上创建一个驻留在文件中的Shell脚本?

[英]How To Create A Shell Script In Unix That Prepends To A File?

I'm trying to create a shell script called sv that will prepend to a file, but the solution I'm using seems to only be good for one use, and them the temporary file is deleted. 我正在尝试创建一个称为sv的shell脚本,该脚本将添加到一个文件中,但是我正在使用的解决方案似乎仅对一种用途有效,并且将它们删除了临时文件。 Is there a way I can make a shell script that will be go to use over and over? 有没有办法使我可以反复使用的shell脚本?

Here's the questions: "Suppose we wish to maintain a list of all the dates when we logged on to our UNIX system. It would be easy to do this by adding the following to the .login file: date >> logdates Unfortunately, the latest date comes at the end of file logdates. I want it at the front; that is, the file should contain login dates from latest to earliest. Write a C shell script sv that will be used as follows: date | sv logdates (This way, the script is quite general, and I can use it for other cases when I want to add things to the front of a file.)" 这里的问题是:“假设我们希望在登录UNIX系统时保留所有日期的列表。将以下内容添加到.login文件中很容易做到这一点:date >> logdates不幸的是,最新的date在文件logdates的末尾。我希望它在最前面;也就是说,该文件应包含从最新到最早的登录日期。编写一个C shell脚本sv,其用法如下:date | sv logdates(这种方式,该脚本非常通用,可以在其他情况下将其添加到文件的开头时使用。)”

Here's the script I've come up with: 这是我想出的脚本:

"#!/bin/sh
cat - logdates  /tmp/out && mv /tmp/out logdates"

This will work once, when I try again the system tells me that /tmp/out doesn't exist. 这将工作一次,当我再次尝试时,系统告诉我/ tmp / out不存在。

Does anyone have any suggestions? 有没有人有什么建议?

Thank you! 谢谢!

Using sponge utility : 使用sponge工具

#!/bin/sh
cat - "$1" | sponge "$1"

Simply use tac ( reverse of cat ) to output a file in reverse 只需使用tac(cat的反向)来反向输出文件

#!/bin/sh
tac logdates > /tmp/out && mv /tmp/out logdates

Your shell script sv could contain the following, where newline is your data read from the | 您的Shell脚本sv可能包含以下内容,其中newline是您从|读取的数据| and $1 is the filename passed to sv : $1是传递给sv的文件名:

#!/bin/sh
read newline
(echo "$newline"; cat $1) > tmp; mv tmp $1

And then you could use it like: 然后您可以像这样使用它:

$ date > logdates
$ date >> logdates
$ cat logdates
Tue Mar 11 22:14:34 CDT 2014
Tue Mar 11 22:14:37 CDT 2014
$ date | ./sv logdates
$ cat logdates
Tue Mar 11 22:14:50 CDT 2014
Tue Mar 11 22:14:34 CDT 2014
Tue Mar 11 22:14:37 CDT 2014

This will only work for one-line appends though, as read is terminated by the newline (/n) character. 但是,这仅适用于单行追加,因为read以换行符(/ n)终止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM