Reputation: 53
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
Upvotes: 2
Views: 172
Reputation: 782683
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"
Upvotes: 1