Sunday, January 9, 2022

[SOLVED] How to replace a space with backslash and space "\ " so bash shell script can read the file name from a .tsv file and perform rsync copy

Issue

I have a script which takes source and destination information from a tsv file separated by space. The first column indicates source file path, and second column is destination. My rsync command reads source and destination information and performs copy operation.

But the issue is source and destination files both contain filename with white space (header-background copy.jpg) and as we know that when bash shell reads a file name (with space), it replace the space with backslash followed by space “\ ”

/data-prod/bigdata/abc/test/1143-1003-004_1143-1003-905/static/common/images/header-background copy.jpg /mapped-data/data20/data3/header-background copy.jpg

My question is how I can replace the space with “\ ” so shell can read it. I tried with using below sed command

sed -r 's/^\s+//;s/\s+/\\ /g' test2.tsv

but there is a problem as above sed command also adds a backslash after the source path. As I have mentioned that my script takes source and destination information from the .tsv file so having a slash added is a problem here. Below is the output of the sed command.

/data-prod/bigdata/abc/test/1143-1003-004_1143-1003-905/static/common/images/header-background\ copy.jpg\ /mapped-data/data20/data3/header-background\ copy.jpg

what I want is something like covert from

/data-prod/bigdata/abc/test/1143-1003-004_1143-1003-905/static/common/images/header-background copy.jpg /mapped-data/data20/data3/header-background copy.jpg

to

/data-prod/bigdata/abc/test/1143-1003-004_1143-1003-905/static/common/images/header-background\ copy.jpg /mapped-data/data20/data3/header-background\ copy.jpg


Solution

Using sed, one way would be to group the match and return it with a back reference appending the back slash

sed 's/\([A-Za-z0-9\/][^\.]*\) /\1\\ /g' input_file
/data-prod/bigdata/abc/test/1143-1003-004_1143-1003-905/static/common/images/header-background\ copy.jpg   /mapped-data/data20/data3/header-background\ copy.jpg


Answered By - HatLess