删除前导和AWK现场尾随空间
我试图除去开头和结尾中的以下 2列空间input.txt的
:
I'm trying to remove leading and trailing space in 2nd column of the below input.txt
:
名称,顺序
结果修剪,工作
结果猫,CAT1
我用下面的 AWK
删除领先,并在第2列尾随空格,但AWK不工作。我缺少什么?
i have used the below awk
to remove leading and trailing space in 2nd column but the awk is not working. What am I missing?
awk -F, '{$2=$2};1' input.txt
这使输出为:
名称,顺序
结果修剪,工作
结果猫,CAT1
首尾空格不会被删除。
如果要修剪所有空格,只有在有一个逗号线,并使用 AWK
,那么下面就为你工作:
If you want to trim all spaces, only in lines that have a comma, and use awk
, then the following will work for you:
awk -F, '/,/{gsub(/ /, "", $0); print} ' input.txt
如果你只是想在第二列中删除空格,改变前pression到
If you only want to remove spaces in the second column, change the expression to
awk -F, '/,/{gsub(/ /, "", $2); print$1","$2} ' input.txt
注意 GSUB
替换的字符在 //
与第二前pression,在变量这是第三个参数 - 和就地这样做
- 换句话说,当它完成时, $ 1,0
(或 $ 2
)已被修改。
Note that gsub
substitutes the character in //
with the second expression, in the variable that is the third parameter - and does so in-place
- in other words, when it's done, the $0
(or $2
) has been modified.
充分说明:
-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
命令尾随空格。虽然给予信贷我会给它的工作原理的解释。
EDIT I want to point out that @BMW's solution is better, as it actually trims only leading and trailing spaces with two successive gsub
commands. Whilst giving credit I will give an explanation of how it works.
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