Bash – How to replace a specific character in one string, with a specific character from another string

bashcommand line

For example: I have string1 = 'abcd', and string2 = 'xwyz'.

I want to replace the 3rd character of string1 ('c') with the 4th character of string2 ('z').

Of course, string indexing starts from 0.

How can I accomplish this?

Best Answer

With bash substring manipulation:

s1="abcd"
s2="xwyz"
s1=${s1:0:2}${s2:3}${s1:3}
  • ${s1:0:2} - the 1st slice containing ab (till the 3rd character c)

  • ${s2:3} - the 4th character of the s2 string to be inserted

  • ${s1:3} - the last (4th) character of the s1 string


Final s1 value:

echo $s1
abzd

Or with GNU awk tool:

gawk -v s2=$s2 -v FPAT='[a-z]' '{$3=substr(s2,4)}1' OFS="" <<< $s1
abzd

  • <<< $s1 - the first string s1 is considered as input content

  • -v s2=$s2 - passing the second string s2 as a variable into awk script

  • FPAT='[a-z]' - regex pattern defining a field value ([a-z] - any alphabetic character)


Alternatively, you could also apply the "empty" field separator FS="" treating each character as separate field:

gawk -v s2=$s2 'BEGIN{ FS=OFS="" }{$3=substr(s2,4)}1' <<< $s1
abzd
Related Question