Ajit Balachandran
Ajit Balachandran

Reputation: 173

Replace pattern with RegEx in sed substitution

I am new to UNIX and I am using the sed command to substitute a pattern in my files.

The file content is:

xyx.filename are in Filename

filename are in Filename and app.filename is in Filename

I want to ignore the string ".filename" (i.e the string filename starting with a ".") and substitute the rest of the filename string (ie filename,Filename..etc) to newname

What regex will be used in the sed command?

Upvotes: 2

Views: 737

Answers (1)

fedorqui
fedorqui

Reputation: 289495

You can use this :

$ sed -r 's/(^|[^.])filename/\1newname/gi' file
xyx.filename are in newname
newname are in newname and app.filename is in newname

Explanation

  • -r is used to catch the groups with just ( ... ) instead of \( ... \).
  • (^|[^.])filename matches anything like filename in the beginning of the file or filename with any character in front that is not the dot ..
  • \1newname it replaces it with newname together with the catched value (the one in front of filename).
  • gi performs the replacement globally and ignoring the case.

Upvotes: 2

Related Questions