Replace strings using sed and regex

I am trying to uncomment the contents of a file using sed, but using regex (for example: [0-9] {1,5})

# one two 12 # three four 34 # five six 56 

The following works:

 sed -e 's/# one two 12/one two 12/g' /file 

However, I would like to use the regular expression pattern to replace all matches without entering numbers, but save the numbers as a result.

+20
source share
6 answers

To run an example question just

 sed 's/^# //' file 

thatโ€™s enough, but if you need to delete a comment only on some lines containing a certain regular expression, you can use a conditional address :

 sed '/regex/s/^# //' file 

Thus, all lines containing regex will not be commented out (if the line starts with # )

... where regex can be [0-9]$ like:

 sed '/[0-9]$/s/^# //' file 

will delete # at the beginning of lines containing the number as the last character.

AND

 sed '/12$/s/^# //' file 

will delete # at the beginning of lines ending in 12 . Or

 sed '/one two/s/^# //' file 

will delete # at the beginning of lines containing one two .

+16
source
 sed -e 's/^#\s*\(.*[0-9].*\)$/\1/g' filename 

must do it.

+7
source

The following sed command will uncomment lines containing numbers:

 sed 's/^#\s*\(.*[0-9]\+.*$\)/\1/g' file 
0
source

If you want these lines to be uninjured, containing numbers, you can use this:

 sed -e 's/^#\s*\(.*[0-9]+.*\)/\1/g' file 
0
source

Is the -i option required for replacement in the corresponding file? I can remove the leading # using the following:

 sed -i "s/^# \(.*\)/\1/g" file 

To uncomment only those lines with comments that end in a sequence of at least one digit, I would use it like this:

 sed -i "s/^# \(.*[[:digit:]]\+$\)/\1/g" file 

This solution requires commented out lines to start with a single space character (right behind the # ), but this should be easy to set up if not applicable.

0
source

I find it. thanks to all of you

 echo "# one two 12" | grep "[0-9]" | sed 's/# //g' 

or

 cat file | grep "[0-9]" | sed 's/# //g' 
-one
source

All Articles