Linux Text Processing – Replace All Characters Except the First Four

linuxsedtext processing

I want to pipe in a command to sed like so:

md5sum input.txt | sed 's/^\(....\).*/\1/;q'

This works by only outputting the first 4 characters of the checksum. However, I want to output the first 4 characters, but also have an x in the place of every other characters (redacting info). I'm so lost now.

Best Answer

With GNU Sed,

md5sum input.txt | sed 's/./x/5g'

This simply skips substituting the 4 first characters of the string and performs the substitution for all other characters.

A POSIX alternative with Awk (although there is probably something simpler),

md5sum xad | awk '{
  four=substr($0, 1, 4)
  rest=substr($0, 5)
  gsub(/./, "x", rest)
  print four, rest
}' OFS=""
Related Question