Sed Replace Forward Slash with Backslash

Sed Replace Forward Slash with Backslash

I have to convert filenames having a forward slash to filenames with a back slash in a makefile using mingw32. I used the following sed command to store the result in a variable:

ORIGINAL=./a/b/main1.c ./a/b/main2.c ./a/b/main3.c

sed command:

RESULT=$(shell echo $(ORIGINAL) | sed 's/\//\\/g')

And the resulting output is:

.\a\b\main1.c .abmain2.c .abmain3.c

It works fine if I run it directly on bash. Can anyone tell me whats wrong?

Thanks!

2

3 Answers

I'm trying to duplicate your test in a makefile, but I don't have your environment. But I would not use '/' as a command separator if I am searching for the same character. Use another character, like ':'

sed 's:/:\\:g'
1
RESULT=$(sed 's/\//\\/g' <<< "$ORIGINAL")


$ ORIGINAL='./a/b/main1.c ./a/b/main2.c ./a/b/main3.c'
$ echo "$ORIGINAL"
./a/b/main1.c ./a/b/main2.c ./a/b/main3.c
$ RESULT=$(sed 's/\//\\/g' <<< "$ORIGINAL")
$ echo $RESULT
.\a\b\main1.c .\a\b\main2.c .\a\b\main3.c
1

Most likely the shell that make is invoking is not bash. However, I find the behavior you're seeing very strange for any shell (it replaces in the first word but not the rest?!?!)

Have you considered using GNU make's $(subst ...) function, instead of the shell?

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.