Replace Strings Using Sed And Regex

94,876

Solution 1

For complying sample question, simply

sed 's/^# //' file

will suffice, but if there is a need to remove the comment only on some lines containing a particular regex, then you could use conditionnal address:

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

So every lines containing regex will be uncomented (if line begin with a #)

... where regex could be [0-9] as:

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

will remove # at begin of every lines containing a number, or

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

to make first space not needed: #one two 12, or even

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

will remove # at begin of lines containing a number as last character. Then

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

will remove # at begin of lines ended by 12. Or

sed '/\b\(two\|three\)\b/s/^# //' file

will remove # at begin of lines containing word two or three.

Solution 2

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

should do it.

Solution 3

If you only want those lines uncommented which contain numbers, you can use this:

sed -e 's/^#\s*\(.*[0-9]+.*\)/\1/g' file
Share:
94,876

Related videos on Youtube

tangi
Author by

tangi

Updated on December 13, 2020

Comments

  • tangi
    tangi over 3 years

    I'm trying to uncomment file content using sed but with regex (for example: [0-9]{1,5})

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

    The following is working:

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

    However, what I would like is to use regex pattern to replace all matches without entering numbers but keep the numbers in the result.

    • Lee Meador
      Lee Meador over 11 years
      How do you define "matches"? Which lines do you want to uncomment and how do you decide that?
    • tangi
      tangi over 11 years
      it should only uncomment text witch contains numbers.
  • tangi
    tangi over 11 years
    the issue here is that this will uncomment everything including text without numbers.
  • cHao
    cHao over 11 years
    I like this; it's a bit clearer about the intent. (You don't want to "replace # + some stuff + a digit + other stuff, with everything but the #"; you want to "remove the # on lines that contain digits".) For regex, you could say [0-9] to have it only affect lines with digits in them, or [0-9]$ if the number has to be at the end.
  • Jonathan Leffler
    Jonathan Leffler over 5 years
    These solutions delete lines which don't contain digits but that were not already uncommented. Maybe there are no such lines (not even any blank lines?), but it arguably isn't wholly appropriate behaviour.
  • F. Hauri  - Give Up GitHub
    F. Hauri - Give Up GitHub over 4 years
    Could by written: sed -e '/[0-9]/s/^# *//' filename! See my answer
  • Seraf
    Seraf over 3 years
    Don't forget to add -i to replace in place, directly in the file, but without that just to check the output