[英]How do you find and replace a line in a text document through terminal
I have a shell script that was created with vim. 我有一个用vim创建的shell脚本。 The only think i know about it is a var name.
唯一的想法我知道它是一个var名称。
Somewhere in the document there is a line: 在文档的某处有一行:
SecondHome='/Users/me/Documents/code/'
The value of this is incorrect, but through shellscripts carrying out new functionality without changing what that shell script does. 这个值是不正确的,但是通过执行新功能的shell脚本而不改变shell脚本的功能。
I was thinking to do something like: 我想做的事情如下:
grep -n "SecondHome" somefile.sh
which will spit out line numbers + the matchs, but only change the first one, as that is the variable definition. 这会吐出行号+匹配,但只改变第一个,因为那是变量定义。
I was thinking to then do a replace on that line somehow to make it look like: 我当时想要在那条线上做一个替换,以使它看起来像:
export SecondHome=$DirPath/code/$Repo
then run the script file which has been modified. 然后运行已修改的脚本文件。
#!/bin/zsh
export DirPath=/Users/me/Documents/
export Repo=MyNewRepo/
export LineNumber=$(grep -n "SecondHome" somefile.sh)
#carry out replace on somefile.sh at $LineNumber with: export SecondHome=$DirPath/code/$Repo/
. ./somefile.sh
is this possible? 这可能吗?
sed -i.bak '/SecondHome=/s,=.*,=$DirPath/code/$Repo,' somefile.sh
sed -i.bak expression file
performs the expression
on the file, modifying it -i
n place. sed -i.bak expression file
进行expression
上的文件,修改它-i
N将。
The expression is on the form /regex/command
, which runs command
on lines that match regex
. 表达式位于表单
/regex/command
,该command
在与regex
匹配的行上运行command
。
The command
is s,search,replace,
, which searches and replaces text. command
是s,search,replace,
,用于搜索和替换文本。
In other words, it modifies files by finding lines containing SecondHome=
, and replacing everything after the equals sign with your string. 换句话说,它通过查找包含
SecondHome=
行来修改文件,并用等号替换等号之后的所有内容。
You can also replace the single quotes with double quotes if your $DirPath/$Repo is defined in the replacement script and not in somefile.sh 如果在替换脚本中定义$ DirPath / $ Repo而不在somefile.sh中,则还可以用双引号替换单引号
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.