title: sed: replacing text between two strings, without editing whole line
body: <p>I am trying to make a Raspberry Pi configurator script (before booting the pi for the first time) and I want implement a feature to set a password. I found out that the password can be set under /etc/shadow but it needs to be encrypted. </p>
  
  <p>Long story short:</p>
  
  <p>How do I replace just the hash between the two strings <strong>pi:</strong> and the second <strong>:</strong> with sed?</p>
  
  <pre><code>pi:$6$FVPr/I.sQGI3ab3z$rmQMzZDghl/.sJyohBZ2B4Z4Bxkr.zOZJ5c4pVJlHTZEGbO28CoXhgPUZ/gds5km3puT9O2b.K0bIjbNeNTSW/:18277:0:99999:7:::
  </code></pre>
  
  <p>The output I want with my script:</p>
  
  <p>e.g. </p>
  
  <pre><code>pi:$6$salty-boi$nt6OkKwSfV4kkk2mcEjEZW1z9rChDK9VeE.c7LE5oFv4Zd.KQbqlN2mSnc9EbcAB.iIlvhRCT10Y6ovLWvaLu.:18277:0:99999:7:::
  </code></pre>
  
  <p>I tried this:</p>
  
  <pre><code>sed -i "s|pi:.*:|pi:$RPI_PASSWD_ENCRYPTED:|g" shadow
  </code></pre>
  
  <p>But the output I get is this:</p>
  
  <pre><code>pi:$6$saltypi$NpLE895oMWEr3R6p9f1dZnekSeJq8QdAk8tQu08rTF3gsnKVoKX7Z.JsNyBCg.o/QamYgzr.w7dVoRyi5nFBM.:
  </code></pre>
  
  <p>Without this afterwards: <code>18277:0:99999:7:::</code></p>
  
  <p>Here's an example of my script:</p>
  
  <pre><code>#!/bin/bash
  exitstatus=$?
  RPI_PASSWD=$(whiptail --inputbox "Type a password for user pi. Press cancel to skip." 8 40 --title "Changing default password" --ok-button "Ok" --cancel-button "Cancel" 3&gt;&amp;1 1&gt;&amp;2 2&gt;&amp;3)
  if [ $exitstatus = 0 ]; then
     RPI_PASSWD_ENCRYPTED=$(openssl passwd -6 -salt saltypi $RPI_PASSWD)
     sed -i "s|pi:.*:|pi:$RPI_PASSWD_ENCRYPTED:|g" shadow
  fi
  exit 1
  </code></pre>
  
  <p><a href="https://github.com/ungeskriptet/Raspberry-Pi-Configurator" rel="nofollow noreferrer">Here's the full code.</a></p>