Andrew Hall
Andrew Hall

Reputation: 139

using variables in regex?

Part of a shell script that I am creating takes a plain text list of files...

 11111.jpg
 22222.jpg
 33333.jpg

...and appends a user-defined prefix that is stored in a variable to create a list of paths that looks like this:

 user/defined/prefix/11111.jpg
 user/defined/prefix/22222.jpg
 user/defined/prefix/33333.jpg

I am attempting to use sed to add the prefix in this manner:

 sed -e 's/^/prefix/' oldFile > newFile.new

The variable is getting assigned correctly:

 echo $selectedPrefix
 user/defined/prefix

Put no combinations of single quotes, double quotes of whatever seem to get sed to use the ACTUAL value of the variable instead of just the variable name.

 sed -e 's/^/$selectedPrefix/' oldFile > newFile.new

Yields:

 $selectedPrefix11111.jpg
 $selectedPrefix22222.jpg
 $selectedPrefix33333.jpg

Help! I'm sure the solution is simple but I feel like I've tried everything....

Upvotes: 0

Views: 56

Answers (2)

Mike
Mike

Reputation: 89

As mentionned by Cyrus, you need to used " (double quote) instead ' (single quote) if you want the variable replacement because single quoted string are interpreted literally so it doesn't see $selectedPrefix as a variable but as the string value of $selectedPrefic hence what you saw.

Since you are working with paths in you sed, you are correct in assuming that you should use a different separator for your sed comment. I usually prefer using | but ~ would also work.

so basically you could have:

sed -e "s~^~$selectedPrefix~" oldFile > newFile.new

Upvotes: 1

Jamil Said
Jamil Said

Reputation: 2093

This code would solve your problem:

selectedPrefixEscaped="$(echo "$selectedPrefix" | sed 's/\//\\\//g')" && sed -e "s/^/$selectedPrefixEscaped/" oldFile > newFile.new

Just using a different delimiter on sed would leave you open to problems when (if) the path contains the new delimiter (ex.: /folder/folder#5/file.txt would be problematic if using # as sed delimiter).

Upvotes: 0

Related Questions