shell – 在awk中删除字段中的前导和尾随空格
发布时间:2020-12-15 19:47:53 所属栏目:安全 来源:网络整理
导读:我正在尝试删除以下input.txt的第2列中的前导和尾部空格: 名称,订单 修剪,工作 猫,猫1 我使用下面的awk来删除第二列中的前导和尾随空格,但是awk不起作用。我缺少什么? awk -F,'{$2=$2};1' input.txt 这给出的输出为: 名称,订单 修剪,工作 猫,猫1
我正在尝试删除以下input.txt的第2列中的前导和尾部空格:
名称,订单 我使用下面的awk来删除第二列中的前导和尾随空格,但是awk不起作用。我缺少什么? awk -F,'{$2=$2};1' input.txt 这给出的输出为: 名称,订单 前导和尾随空格不被删除。
如果要修剪所有空格,只能使用逗号分隔,并使用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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |