Replace Trailing White Space with Underscore in Linux

awklinuxsedtext processing

I'm wanting to replace each character of white space at the end of each line with '_'. I found a similar question and answer for leading whitespace. But have failed to reconstruct it for trailing whitespace. Here's the link: https://stackoverflow.com/questions/9222281/replace-leading-whitespace-with-sed-or-similar

If anyone can think of a quicker or better way, that would also be great. I also appreciate good explanations, as that way I learn quicker 🙂

Input:
foo bar
 foo bar oof
  line 3a  
  line fo a

Output:
foo bar_____
 foo bar oof
  line 3a___
  line fo a_

Best Answer

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_
Related Question