Thursday, April 28, 2022

[SOLVED] how to regex replace before colon?

Issue

this is my original string:

NetworkManager/system connections/Wired 1.nmconnection:14 address1=10.1.10.71/24,10.1.10.1

I want to only add back slash to all the spaces before ':'

so, this is what I finally want:

NetworkManager/system\ connections/Wired\ 1.nmconnection:14 address1=10.1.10.71/24,10.1.10.1

I need to do this in bash, so, sed, awk, grep are all ok for me.

I have tried following sed, but none of them work

echo NetworkManager/system connections/Wired 1.nmconnection:14 address1=10.1.10.71/24,10.1.10.1 | sed 's/ .*\(:.*$\)/\\ .*\1/g'
echo NetworkManager/system connections/Wired 1.nmconnection:14 address1=10.1.10.71/24,10.1.10.1 | sed 's/\( \).*\(:.*$\)/\\ \1.*\2/g'
echo NetworkManager/system connections/Wired 1.nmconnection:14 address1=10.1.10.71/24,10.1.10.1 | sed 's/ .*\(:.*$\)/\\ \1/g'
echo NetworkManager/system connections/Wired 1.nmconnection:14 address1=10.1.10.71/24,10.1.10.1 | sed 's/\( \).*\(:.*$\)/\\ \1\2/g'

thanks for answering my question. I am still quite newbie to stackoverflow, I don't know how to control the format in comment. so, I just edit my original question

my real story is:

when I do grep or use cscope to search keyword, for example "address1" under /etc folder. the result would be like:

./NetworkManager/system connections/Wired 1.nmconnection:14 address1=10.1.10.71/24,10.1.10.1

if I use vim to open file under cursor, suppose my vim cursor is now at word "NetworkManager", then vim will understand it as

"./NetworkManager/system"

that's why I want to add "\" before space, so the search result would be more vim friendly:)

I did try to change cscope's source code, but very difficult to fully achieve this. so have to do a post replacement:(


Solution

If you only want to do the replacements if there is a : present in the string, you can check if there are at least 2 columns, setting the (output)field separator to a colon.

Data:

cat file                                                                                                                                       michaelvandam@Michaels-MacBook-Pro
NetworkManager/system connections/Wired 1.nmconnection:14 address1=10.1.10.71/24,10.1.10.1
NetworkManager/system connections/Wired 1.nmconnection 14 address1=10.1.10.71/24,10.1.10.1%

Example in awk:

awk 'BEGIN {FS=OFS=":"}{if(NF>1)gsub(" ","\\ ",$1)}1' file

Output

NetworkManager/system\ connections/Wired\ 1.nmconnection:14 address1=10.1.10.71/24,10.1.10.1
NetworkManager/system connections/Wired 1.nmconnection 14 address1=10.1.10.71/24,10.1.10.1


Answered By - The fourth bird
Answer Checked By - Katrina (WPSolving Volunteer)