简体   繁体   English

使用SED在搜索条件后替换变化的字符串

[英]Replacing a varying string after search criteria using SED

Inside a shell script amidst error checking loops, I have a command that contains a variable that must be updated once an hour. 在错误检查循环中的shell脚本中,我有一个命令,其中包含一个必须每小时更新一次的变量。 The command as it exists currently is (the line begins with a \\t): 当前存在的命令是(该行以\\ t开头):

        /home/user/therm/therm -d /dev/ttyUSB0 -t host -O 44.0

In this case, I'm trying to replace the number that's after "-O". 在这种情况下,我试图替换“ -O”之后的数字。 This is a temperature in Fahrenheit, so it has the possibility of being a negative number or a positive number, and one, two, or three digits followed by a single decimal place. 这是华氏温度,因此有可能是负数或正数,以及一个,两个或三个数字后跟一个小数位。 So I have to be able to replace a variable that could be "-15.0", "7.2", "104.5", or any other combination - with a new variable that could also be any of the above. 因此,我必须能够用新的变量替换“ -15.0”,“ 7.2”,“ 104.5”或任何其他组合的变量,也可以是上述任意变量。

I can force the "-O" setting to be the last thing on the line, which helps some. 我可以强制将“ -O”设置设置为行中的最后一项,这有所帮助。 But I can't count on anything else on that line except the file name, the "-d /dev/ttyUSB0" and the "-O" always being there. 但是除了文件名,“-d / dev / ttyUSB0”和“ -O”始终在那里,我不能指望该行上的其他任何东西。 In this particular shell script there are no other instances of "-O", but I might want to verify that the line has either the file name or the "-d /dev/ttyUSB0" on it to avoid replacing a flag on some other line in the script. 在此特定的shell脚本中,没有其他“ -O”实例,但我可能想验证该行上是否包含文件名或“ -d / dev / ttyUSB0”,以避免替换其他标记脚本中的一行。

The new variable is parsed (via xmllint and sed) from an XML file grabbed via wget once an hour. 每小时从wget抓取的XML文件中(通过xmllint和sed)解析新变量。 This shell script I need to edit is ran by cron every 5 minutes, only receiving the new string once an hour. 我需要编辑的这个Shell脚本每5分钟由cron运行一次,每小时仅接收一次新字符串。 The new string can be passed to sed via a variable, or as a file with only the number and a \\n in it. 新字符串可以通过变量或作为仅包含数字和\\ n的文件传递给sed。

Any thoughts or brilliant ideas would be appreciated. 任何想法或好主意将不胜感激。 Thanks. 谢谢。

You can use this sed command: 您可以使用以下sed命令:

# string to be replaced
r=123.4
sed "s/\(-O *\)[^[:blank:]]*/\1$r/" file
/home/user/therm/therm -d /dev/ttyUSB0 -t host -O 123.4

Pattern -O *[^[:blank:]]* will find literal -O followed by 0 or more spaces and then the non-space string. 模式-O *[^[:blank:]]*将找到文字-O后跟0或多个空格,然后是非空格字符串。

这似乎有效

awk '{$NF=($NF-32)/1.8;print}'

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

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