2

I am new to Bash and am trying to create a bash function that can:

1) Find all file names matching that which is given ($1) recursively in my current directory's sub-folders

2) Locate and replace the whole line matching the pattern in a variable string ($2) with a second variable string ($3)

I think I am most of the way there, but am having trouble with replacing text strings containing spaces. My current function looks like:

rplcPhrase() {
    find . -name $1 -exec sed -i "/$2/c $3" {} + 
}

rplcPhrase $1 $2 $3

and command line input looks like

/link/to/file.sh "filetochange.txt" "\!phrase[[:space:]]to[[:space:]]change" "replacement[[:space:]]phrase"

Researching similar questions have explained the need to "escape" special characters (such as "!") in order to use in the pattern and that [[:space:]] must be used in the search pattern to account for spaces. However, I would like to return a phrase that contains a space. The result of the above command line input correctly finds the pattern

!phrase to change

but replaces it with

replacement[[:space:]]phrase

If I instead change replacement[[:space:]]phrase with replacement phrase, it only yields

replacement

Like I said, I feel like I'm almost there and am just missing something simple. Any help would be appreciated.

I've already searched for this and cannot find a solution that quite solves my problem. See links: Replace whole line containing a string using Sed

Using sed to replace text with spaces with a defined variable with slashs

2
  • 2
    Quote your variables. Commented Jun 21, 2017 at 17:20
  • @Barmar where should I quote the variables? Within the sed command (sed -i "/"$2"/c "$3"")? Commented Jun 21, 2017 at 17:28

1 Answer 1

1

You need to quote the variables to prevent word splitting and wildcard expansion.

rplcPhrase() {
    find . -name "$1" -exec sed -i "/$2/c $3" {} + 
}

rplcPhrase "$1" "$2" "$3"
Sign up to request clarification or add additional context in comments.

1 Comment

That fixed it. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.