Using sed to backslash forward slashes

I needed to extract the devices from the /etc/fstab so I could feed them into a sed replacement. Of course I needed to backslash the forward slashes in the device path before I could use them with sed. Here is what I used to insert the backslashes into the device paths.

This works on the bash shell command line:

$ echo /dev/mapper/rootvg-root |  sed 's/\//\\\//g' 
\/dev\/mapper\/rootvg-root

These 2 methods work from within a bash script:

$ cat test.sh
#!/usr/bin/bash

device1=`echo /dev/mapper/rootvg-root |  sed 's/\//\\\\\//g'`
device2=$(echo /dev/mapper/rootvg-root |  sed 's/\//\\\//g')
echo $device1
echo $device2

$ ./test.sh
\/dev\/mapper\/rootvg-root
\/dev\/mapper\/rootvg-root

You may also like...