shell – 在awk中删除字段中的前导和尾随空格

我正在尝试删除以下input.txt的第2列中的前导和尾部空格:

名称,订单
修剪,工作
猫,猫1

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

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

这给出的输出为:

名称,订单
修剪,工作
猫,猫1

前导和尾随空格不被删除

如果要修剪所有空格,只能使用逗号分隔,并使用awk,那么以下内容将适用于您:
awk -F,'/,/{gsub(/ /,"",$0); print} ' input.txt

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

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

请注意,gsub将第二个表达式中的字符替换为第三个参数的变量,并且就地存在 – 换句话说,当完成时,$ 0(或$ 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

编辑我想指出,@宝马的解决方案更好,因为它实际上只修剪了两个连续的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

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...