[英]Using “sed” command in linux to replace text
I have a specific question related to the usage of sed in linux. 我有一个与linux中sed用法有关的特定问题。
Suppose there is a String "Hello to the world version 1.0.0.1" 假设有一个字符串“世界版本1.0.0.1的问候”。
Now I want to take the new version from a file and update this 现在,我想从文件中获取新版本并进行更新
For example the new version is present in /etc/NewVersion 例如,新版本位于/ etc / NewVersion中
So can we do something like this : 所以我们可以做这样的事情:
$newVersion = "/etc/NewVersion"
sed -i "s/1.0.0.1/$newVersion/g" /etc/motd
Also is there a way that suppose the last number of the version changes, from 1.0.0.1 to something else like 1.0.0.2 , how can i make it generic that no matter what the version Im able to fetch the new version from the file path and update it with sed? 还有一种方法可以假设版本的最后一次更改,从1.0.0.1到其他类似1.0.0.2的版本,无论什么版本,我如何都能将其通用化我可以从文件路径中获取新版本并用sed更新它?
sed doesn't really support passing parameters very well. sed并不能很好地支持传递参数。 A better solution would be awk:
一个更好的解决方案将是awk:
awk -v overs="1.0.0.1" -v newver="1.0.0.2" '$0 ~ overs { flag=0;match($0,overs);print substr($0,1,RSTART-1)newver } $0 !~ overs { flag=1 } flag' /etc/motd
Pattern match for the old version number. 旧版本号的模式匹配。 If it exists, stop the line printing by setting flag=0.
如果存在,则通过设置标志= 0停止行打印。 Then match the old version number and print the rest of the line plus the new version number.
然后匹配旧版本号,并打印该行的其余部分以及新版本号。 Otherwise, set flag=1 and print the line.
否则,设置flag = 1并打印该行。
With sed and a bash command substitution to read from /etc/NewVersion
, and assuming that your New Version text will never contain a forward-slash: 使用sed和bash 命令替换从
/etc/NewVersion
,并假定您的New Version文本永远不会包含正斜杠:
sed -i "s/\(Hello to the world version \).*/\1"$(</etc/NewVersion)"/" /etc/motd
This replaces (with -i
"in-place" editing of /etc/motd) the string "Hello to the world version ", followed by anything, with the "Hello" text (captured with the parenthesis and referred to by the \\1
, followed by the contents of /etc/NewVersion
. 这将替换字符串“ Hello to the world version”(用/
-i
/ motd的-i
“就地”编辑),后跟所有内容,并替换为“ Hello”文本(用括号捕获并用\\1
,然后是/etc/NewVersion
的内容。
Or, if you want to allow any contents in /etc/NewVersion
, use ed : 或者,如果要允许
/etc/NewVersion
任何内容,请使用ed :
ed -s /etc/motd <<< $'1c\nHello to the world version '"$(</etc/NewVersion)"$'\n.\nwq'
This edits /etc/motd in script ( -s
) mode, passing it the quoted string as input (commands for ed): 这将以脚本(
-s
)模式编辑/ etc / motd,并将加引号的字符串作为输入传递给它(ed的命令):
1
, c
hange it to: 1
, c
它焊割到: Hello to the world version
followed by the contents of /etc/NewVersion Hello to the world version
后面是/ etc / NewVersion的内容 .
stop input mode for the c
command c
命令的输入模式 w
rite and q
uit w
仪式和q
UIT
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.