简体   繁体   中英

How do you find and replace a line in a text document through terminal

I have a shell script that was created with vim. The only think i know about it is a var name.

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.

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.

The expression is on the form /regex/command , which runs command on lines that match regex .

The command is s,search,replace, , which searches and replaces text.

In other words, it modifies files by finding lines containing SecondHome= , and replacing everything after the equals sign with your string.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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