用'_'替换每行末尾的每个空格字符

Gil*_*les 6 linux sed awk text-processing

我想用'_'替换每行末尾的每个空格字符。我发现了一个类似的问题和答案,用于引导空白。但未能为尾随空格重建它。这是链接:https : //stackoverflow.com/questions/9222281/replace-leading-whitespace-with-sed-or-similar

如果有人能想到更快或更好的方法,那也太好了。我也很欣赏好的解释,因为这样我学得更快:)

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

Output:
foo bar_____
 foo bar oof
  line 3a___
  line fo a_
Run Code Online (Sandbox Code Playgroud)

Ger*_*lle 9

使用 GNU sed,用下划线替换 eol 处的所有空格:

sed ':x;s/ \( *\)$/_\1/;tx'  
Run Code Online (Sandbox Code Playgroud)


Ed *_*ton 3

使用 GNU awk 将第三个参数传递给 match() 和 gensub():

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

对于任何 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_
Run Code Online (Sandbox Code Playgroud)

要通过调整上面的 gawk 解决方案来替换前导空白:

$ 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_
Run Code Online (Sandbox Code Playgroud)