I have a file that contains filenames with absolute path.
In the middle of that path, is a variable directory, whenever I hard code the variable part, it works fine, but when I replace it with the variable name, the sed part doesn’t work.
The sed part is to delete the pattern or for this matter, the path.
file=`echo $one_file | sed 's:/dir1/dir2/$VAR/last_dir/::'`
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
When you use single-quotes, aka hard quotes, variable names are not expanded. You would need to use double-quotes, aka soft quotes.
sed "s:/dir1/dir2/$var/Last_dir/::"
or escape the quotes:
sed 's:/dir1/dir2/'"$var"'/Last_dir/::'
You would also need to be sure that $var does not hold any colon, dot, star, [, newline or backslash characters or that, if it does, they are escaped.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0