如果您想修剪所有空格,仅在有逗号的行中,并使用awk,那么以下内容将适合您:
awk -F, '/,/{gsub(/ /, "", $0); print} ' input.txt
如果你只想删除第二列中的空格,请将表达式更改为
awk -F, '/,/{gsub(/ /, "", $2); print$1","$2} ' input.txt
请注意,gsub 将 // 中的字符替换为第三个参数的变量中的第二个表达式 - 并且这样做了 in-place - 换句话说,当它完成时,$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
编辑 我想指出@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