在 awk 中修剪字符串的前导和尾随空格

2023-12-08

我正在尝试删除下面第二列中的前导和尾随空格input.txt:

Name, Order  
Trim, working
cat,cat1

我用过下面的awk删除第二列中的前导和尾随空格,但它不起作用。我缺少什么?

awk -F, '{$2=$2};1' input.txt

输出如下:

Name, Order  
Trim, working
cat,cat1

前导空格和尾随空格不会被删除。


如果您想修剪所有空格,仅在有逗号的行中,然后使用awk,那么以下内容将适合您:

awk -F, '/,/{gsub(/ /, "", $0); print} ' input.txt

如果您只想删除第二列中的空格,请将表达式更改为

awk -F, '/,/{gsub(/ /, "", $2); print$1","$2} ' input.txt

注意gsub替换中的字符//与第二个表达式,在作为第三个参数的变量中 - 并且这样做in-place- 换句话说,当它完成后,$0 (or $2)已被修改。

完整解释:

-F,            use comma as field separator 
               (so the thing before the first comma is $1, etc)
/,/            operate only on lines with a comma 
               (this means empty lines are skipped)
gsub(a,b,c)    match the regular expression a, replace it with b, 
               and do all this with the contents of c
print$1","$2   print the contents of field 1, a comma, then field 2
input.txt      use input.txt as the source of lines to process

EDIT我想指出 @BMW 的解决方案更好,因为它实际上仅修剪两个连续的前导和尾随空格gsub命令。在给予认可的同时,我将解释它是如何工作的。

gsub(/^[ \t]+/,"",$2);    - starting at the beginning (^) replace all (+ = zero or more, greedy)
                             consecutive tabs and spaces with an empty string
gsub(/[ \t]+$/,"",$2)}    - do the same, but now for all space up to the end of string ($)
1                         - ="true". Shorthand for "use default action", which is print $0
                          - that is, print the entire (modified) line
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 awk 中修剪字符串的前导和尾随空格 的相关文章

随机推荐