Sed: Use Variables Containing Paths

Posted May 19, 2020 by Yaroslav Grebnov ‐ 2 min read

The task is to replace some sequence of characters by another sequence constructed dynamically, using a variable value, in all files located in the current directory.

The current directory is myDirectory, which is located in the tuser’s home directory:

[tuser@centos myDirectory]$ pwd
/home/tuser/myDirectory

myDirectory contains three files: file1, file2, and file3:

[tuser@centos myDirectory]$ ls
file1  file2  file3

Each file contains the same sequence of characters: textToReplace

[tuser@centos myDirectory]$ cat file1
textToReplace
[tuser@centos myDirectory]$ cat file2
textToReplace
[tuser@centos myDirectory]$ cat file3
textToReplace

textToReplace will be replaced by: File location: $HOME/myDirectory. HOME variable value:

[tuser@centos myDirectory]$ echo $HOME
/home/tuser

An attempt to execute a sed command with slashes with result in an error:

[tuser@centos myDirectory]$ for file in $( ls -1 ); do sed "s/textToReplace/File location: $HOME\/myDirectory/g" -i $file; done
sed: -e expression #1, char 33: unknown option to `s'
sed: -e expression #1, char 33: unknown option to `s'
sed: -e expression #1, char 33: unknown option to `s'

The solution is to use pipes instead of slashes in the sed command:

[tuser@centos myDirectory]$ for file in $( ls -1 ); do sed "s|textToReplace|File location: $HOME\/myDirectory|g" -i $file; done
[tuser@centos myDirectory]$ 

Files contain File location: /home/tuser/myDirectory, as expected:

[tuser@centos myDirectory]$ cat file1
File location: /home/tuser/myDirectory
[tuser@centos myDirectory]$ cat file2
File location: /home/tuser/myDirectory
[tuser@centos myDirectory]$ cat file3
File location: /home/tuser/myDirectory