duxsco
duxsco

Reputation: 361

Replace every dot with underscore if whitespace/newline not before and after

Let's say I have the following file

asdfa .a
xsf. asdfa
 . xasdf
asdfasfd.sadfa.
asdfa .a
xsf. asdfa
 . 3xasdf
asdfasfd2.sadfa.

And, I want to get this:

asdfa .a
xsf. asdfa
.xasdf
asdfasfd_sadfa.
asdfa .a
xsf. asdfa
 . 3xasdf
asdfasfd2_sadfa.

Basically, every dot has to be replaced with an underscore if all following conditions are true:

  1. There is no blank character as well as tab before and after the dot.
  2. The dot is not at the beginning of the line.
  3. The dot is not at the end of the line.

Update: So, far I could only come up with sed 's/\./_/g'. But, this replaces every dot.

Upvotes: 0

Views: 55

Answers (2)

Matt Spaulding
Matt Spaulding

Reputation: 60

I think this should do the trick

sed -i 's/\(\w\)\(\.\)\(\w\)/\1_\3/g' mytextfile.txt

Upvotes: 1

karakfa
karakfa

Reputation: 67567

here sed shines

$ sed -r 's/(\S)\.(\S)/\1_\2/g' file

Upvotes: 2

Related Questions