Replace each character of white space at the end of each line with '_'

With GNU sed, replacing all spaces at eol by underscore:

sed ':x;s/ \( *\)$/_\1/;tx'  

More efficient to use perl:

perl -lpe 's/(\s+)$/"_" x length($1)/e' input.txt

which only has to do one substitution per line with trailing whitespace, instead of looping.


With GNU awk for the 3rd arg to match() and gensub():

$ awk 'match($0,/(.*[^ ])(.*)/,a){$0=a[1] gensub(/ /,"_","g",a[2])} 1' file
foo bar_____
 foo bar oof
  line 3a___
  line fo a_

With any awk:

$ awk 'match($0,/ +$/){tail=substr($0,RSTART,RLENGTH); gsub(/ /,"_",tail); $0=substr($0,1,RSTART-1) tail} 1' file
foo bar_____
 foo bar oof
  line 3a___
  line fo a_

To replace leading blanks too by tweaking the above gawk solution:

$ awk 'match($0,/^( *)(.*[^ ])(.*)/,a){$0=gensub(/ /,"_","g",a[1]) a[2] gensub(/ /,"_","g",a[3])} 1' file
foo bar_____
_foo bar oof
__line 3a___
__line fo a_