Replace spaces or - with _ if the string starts with a digit

I have a text file as follows:

#1xx Informational responses
100=Continue
101=Switching Protocols
102=Processing
#2xx Success
200=OK
201=Created
202=Accepted
203=Non-Authoritative Information
204=No Content
205=Reset Content
206=Partial Content
207=Multi-Status
208=Already Reported
226=IM Used   

      

What I want to do is convert this to the following:

#1xx_Informational responses
100=Continue
101=Switching_Protocols
102=Processing
#2xx_Success
200=OK
201=Created
202=Accepted
203=Non_Authoritative_Information
204=No_Content
205=Reset_Content
206=Partial_Content
207=Multi_Status
208=Already_Reported
226=IM_Used

      

I could use:

:%s/[ \|-]/_/g  

      

but it unconditionally changes spaces or - with _ on all lines, including the first line:

#1xx_Informational_responses

      

I do not want it. Instead, I want to replace spaces and - with _ only if the string starts with a digit. For all other strings, I don't want to perform a replace operation.

Is there a way to "conditionally" perform a replace operation? I don't want to deal with line numbers, line numbers can change. I want answers regarding the content of the line (starting with a digit for this case), not the line number.

Thanks in advance.

+3


source to share


2 answers


:g/^\d/s/[ -]/_/g

      

The command :global

runs the command for each line that matches the given regular expression.



(By the way, your regex [ \|-]

matches a character that is either a space or \

or |

or -

.)

+6


source


Try piping it through sed, which lets you pick lines to work on

:%!sed '/^[0-9]/s/-/_/g'

      



this string selects all lines starting with a digit and then replaces all (as option g

) -

characters with _

.

0


source







All Articles