如果您想修剪所有空格,仅在有逗号的行中,然后使用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