Replace Strings Using Sed And Regex

前端 未结 6 1910
猫巷女王i
猫巷女王i 2020-12-28 14:57

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 fol

相关标签:
6条回答
  • 2020-12-28 15:13

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

    sed -e 's/^#\s*\(.*[0-9]+.*\)/\1/g' file
    
    0 讨论(0)
  • 2020-12-28 15:14

    The following sed command will uncomment lines containing numbers:

    sed 's/^#\s*\(.*[0-9]\+.*$\)/\1/g' file
    
    0 讨论(0)
  • 2020-12-28 15:23

    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.

    0 讨论(0)
  • 2020-12-28 15:27

    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'
    
    0 讨论(0)
  • 2020-12-28 15:32

    Is the -i option for replacement in the respective file not necessary? I get to remove leading # by using the following:

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

    In order to uncomment only those commented lines that end on a sequence of at least one digit, I'd use it like this:

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

    This solution requires commented lines to begin with one space character (right behind the #), but that should be easy to adjust if not applicable.

    0 讨论(0)
  • 2020-12-28 15:36
    sed -e 's/^#\s*\(.*[0-9].*\)$/\1/g' filename
    

    should do it.

    0 讨论(0)
提交回复
热议问题