Properly escaping forward slash in bash script for usage with sed
20,801
You don't actually need to bother with escaping the /
. From the GNU sed
manual:
The
/
characters may be uniformly replaced by any other single character within any givens
command.
For example:
echo 'foobar' | sed -e 's#foo#bar#'
gives the output
barbar
Related videos on Youtube
Author by
user331839
Updated on September 18, 2022Comments
-
user331839 over 1 year
I'm trying to determine the size of the files that would be newly copied when syncing two folders by running rsync in dry mode and then summing up the sizes of the files listed in the output of rsync.
Currently I'm stuck at prefixing the files by their parent folder. I found out how to prefix lines using sed and how to escape using sed, but I'm having troubles combining those two.
This is how far I got:
source="/my/source/folder/" target="/my/target/folder/" escaped=`echo "$source" | sed -e 's/[\/&]/\\//g'` du `rsync -ahnv $source $target | tail -n +2 | head -n -3 | sed "s/^/$escaped/"` | awk '{i+=$1} END {print i}'
This is the output I get from bash -x myscript.sh
+ source=/my/source/folder/ + target=/my/target/folder ++ echo /my/source/folder/ ++ sed -e 's/[\/&]/\//g' + escaped=/my/source/folder/ + awk '{i+=$1} END {print i}' ++ rsync -ahnv /my/source/folder/ /my/target/folder/ ++ sed 's/^//my/source/folder//' ++ head -n -3 ++ tail -n +2 sed: -e expression #1, char 8: unknown option to `s' + du 80268
Any ideas on how to properly escape would be highly appreciated.
-
Clearer over 9 yearsThis should be the first thing in the man page for sed