Ubuntu – Replace spaces in a matched substring with underscores

command linesed

I'm new to the forum so please forgive any syntactical errors in my question.

I'm trying to replace spaces with underscores in a matched substring only. I figured sed would be the best editor for this but I cannot find the proper code to do this.

Sample line from file1 below:

Some text before pattern to match href="./Dynamic Directory name –
Junk_files
/irrelevant stuff after match">

Would like to change to this:

Some text before pattern to match
href="./Dynamic_Directory_name_-_Junk_files/irrelevant stuff after
match">

I thought I was close with this cat file1 |sed '/\.\/.*. Junk_files/ { s/ /_/g; }' but all it did was replace all spaces on the matched line with underscores.

Any help with this would be greatly appreciate. Thanks

Best Answer

Through python,

$ echo 'href="./Dynamic Directory name - Junk_files/irrelevant stuff after match"' |
> python -c "import re;
> import sys;
> print re.sub(r'(?<=\./).*?(?=/)', lambda m: m.group().replace(' ', '_'), sys.stdin.read())
> "
href="./Dynamic_Directory_name_-_Junk_files/irrelevant stuff after match"

Through perl,

$ echo 'href="./Dynamic Directory name - Junk_files/irrelevant stuff' | perl -pe '
> s/\s(?=(?:(?!\.\/).)*?\/)/_/g
> '
href="./Dynamic_Directory_name_-_Junk_files/irrelevant stuff