Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 686
tangi Avatar asked Dec 28 '12 16:12

tangi


People also ask

Can you use regex with sed?

Although the simple searching and sorting can be performed using sed command, using regex with sed enables advanced level matching in text files. The regex works on the directions of characters used; these characters guide the sed command to perform the directed tasks.

How do you use sed to match word and perform find and replace?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

How can I replace text after a specific word using sed?

The following `sed` command shows the use of 'c' to replace everything after the match. Here, 'c' indicates the change. The command will search the word 'present' in the file and replace everything of the line with the text, 'This line is replaced' if the word exists in any line of the file.

Can I use regex in replace?

How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.


1 Answers

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.

like image 89
F. Hauri Avatar answered Sep 18 '22 13:09

F. Hauri