Reputation: 31
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?
Upvotes: 2
Views: 233
Reputation: 133458
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
Upvotes: 2
Reputation: 785108
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
Upvotes: 2
Reputation: 11217
Substitute any character in the 7th position using sed
$ sed 's/./D/7' input_file
AKASHMDNDAL
Upvotes: 4
Reputation: 2093
You can simply match one character outside of the capture group:
sed -E 's/^(.{6})./\1D/'
(notice the dot outside the parenthesis)
Upvotes: 3