Fallenreaper
Fallenreaper

Reputation: 10682

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?

Upvotes: 0

Views: 107

Answers (1)

that other guy
that other guy

Reputation: 123400

sed -i.bak '/SecondHome=/s,=.*,=$DirPath/code/$Repo,' somefile.sh

sed -i.bak expression file performs the expression on the file, modifying it -in 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

Upvotes: 2

Related Questions