将输出文本文件字符串更新为命令行参数时出现批处理脚本问题
我是巴赫脚本的新手。以下是我用来搜索通过命令行输入的名称并在 outputLog.txt 中搜索输入的字符串的代码。如果找到,则更新该名称字符串的当前系统时间。
在命令行中
[root@localhost Desktop]# ./myscript.sh name1
Logone2.txt
name1 = Tue Jan 20 14:00 19 IST 2012
name2 =Tue Jan 20 14:05 19 IST 2012
name3 = Tue Jan 20 14:20 19 IST 2012
name4 =Tue Jan 20 14:45 19 IST 2012
我的问题是当我尝试输入 name1 时,它会使用当前系统时间进行更新,并且它会作为最后一个条目附加。
Eg:Logone2.txt
name1 = Tue Feb 20 14:00 19 IST 2012
name2 =Tue Jan 20 14:05 19 IST 2012
name3 = Tue Jan 20 14:20 19 IST 2012
name4 =Tue Jan 20 14:45 19 IST 2012
name1 = Tue Feb 20 14:00 19 IST 2012 (appended entry)
我只想在 Logone2.txt 中找不到当前系统时间的字符串。如果在 Logone2.txt 中找到通过命令行输入的字符串(name1),请使用当前系统时间更新名称,如下所示。
Eg:Logone2.txt
name1 = Tue Feb 20 14:00 19 IST 2012
name2 =Tue Jan 20 14:05 19 IST 2012
name3 = Tue Jan 20 14:20 19 IST 2012
name4 =Tue Jan 20 14:45 19 IST 2012
这是我使用的代码
#!/bin/bash
echo "${1} $(date)" >> /root/Desktop/scripts/Logone2.txt
fgrep "${1}" /root/Desktop/scripts/Logone2.txt && \
sed -i "/${1}/ s/.*/${1} = $(date)/" /root/Desktop/scripts/Logone2.txt || \
echo "${1} $(date)" >> /root/Desktop/scripts/Logone2.txt
Iam new to bach script. following is the code i used to search the name entered through command line and search the entered string in outputLog.txt .if found update the current system time of that name string.
In command line
[root@localhost desktop]# ./myscript.sh name1
Logone2.txt
name1 = Tue Jan 20 14:00 19 IST 2012
name2 =Tue Jan 20 14:05 19 IST 2012
name3 = Tue Jan 20 14:20 19 IST 2012
name4 =Tue Jan 20 14:45 19 IST 2012
My problem is while i trying to enter name1,it is updated with the current system time also its is appending as last entry.
Eg:Logone2.txt
name1 = Tue Feb 20 14:00 19 IST 2012
name2 =Tue Jan 20 14:05 19 IST 2012
name3 = Tue Jan 20 14:20 19 IST 2012
name4 =Tue Jan 20 14:45 19 IST 2012
name1 = Tue Feb 20 14:00 19 IST 2012 (appended entry)
I only want to append the string with current system time if it is not found in the Logone2.txt.IF the string(name1) entered through command line is found in the Logone2.txt ,update the name with current system time as follows.
Eg:Logone2.txt
name1 = Tue Feb 20 14:00 19 IST 2012
name2 =Tue Jan 20 14:05 19 IST 2012
name3 = Tue Jan 20 14:20 19 IST 2012
name4 =Tue Jan 20 14:45 19 IST 2012
Here is the code iam using
#!/bin/bash
echo "${1} $(date)" >> /root/Desktop/scripts/Logone2.txt
fgrep "${1}" /root/Desktop/scripts/Logone2.txt && \
sed -i "/${1}/ s/.*/${1} = $(date)/" /root/Desktop/scripts/Logone2.txt || \
echo "${1} $(date)" >> /root/Desktop/scripts/Logone2.txt
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我做对了,我的第一个想法是重写整个文件,用 sed 替换 name1 。例如
if i got it right my first idea is to rewrite the entire file replacing name1 with sed. e.g.