How to replace a fixed position character of a string?

Viewed 62

Suppose I have a file having a string AKASHMANDAL

I want to replace 7th positioned character (whatever the character may be) with "D"

Output will looks like

AKASHMDNDAL

I tried with the following command which only add the character after 7th position

sed -E 's/^(.{7})/\1D/' file

This gives me AKASHMADNDAL

How can I replace the character instead of just adding?

4 Answers

Substitute any character in the 7th position using sed

$ sed 's/./D/7' input_file
AKASHMDNDAL

You can simply match one character outside of the capture group:

sed  -E 's/^(.{6})./\1D/'

(notice the dot outside the parenthesis)

If you can consider an awk solution. awk can handle it better without regex and with more power to tweak based on positions:

awk '{print substr($0,1,6) "D" substr($0,8)}' file

AKASHMDNDAL

With your shown samples only, please try following awk code. Written and tested in GNU awk. Here is the Online demo for used awk code here.

awk -v RS='^.{7}' '
RT{
  sub(/.$/,"",RT)
  ORS=RT"D"
  print
}
END{
  ORS=""
  print
}
' Input_file
Related