简体   繁体   中英

Replace Strings Using Sed And Regex

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.

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 .

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

应该这样做。

如果您只想取消注释包含数字的那些行,您可以使用以下命令:

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

以下sed命令将取消注释包含数字的行:

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

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.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM