如何删除前导和尾随空格? [英] How to remove leading and trailing whitespaces?
问题描述
我正在使用 awk'{gsub(/^ [\ t] + | [\ t] + $/,");打印;}'in.txt>out.txt
删除开头和结尾的空格.
I'm using awk '{gsub(/^[ \t]+|[ \t]+$/,""); print;}' in.txt > out.txt
to remove both leading and trailing whitespaces.
问题在于输出文件实际上有尾随空格!所有行的长度都是相同的-正确地用空格填充.
The problem is the output file actually has trailing whitespaces! All lines are of the same length - they are right padded with spaces.
我想念什么?
更新1
问题可能是由于尾随空格也不是正常"空格而是\ x20个字符(DC4).
The problem is probably due to the the fact that the trailing spaces are nor "normal" spaces but \x20 characters (DC4).
更新2
我使用了 gsub(/'[[:: cntrl:]] | [[:space:]] | \ x20/,")
,它可以正常工作.两件奇怪的事情:
I used gsub (/'[[:cntrl:]]|[[:space:]]|\x20/,"")
an it worked.
Two strange things:
-
为什么\ x20不被视为控制字符?
Why isn't \x20 considered a control character?
使用'[[:cntrl:] [:space:] \ x20
不起作用.为什么?
Using '[[:cntrl:][:space:]\x20
does NOT work. Why?
推荐答案
此命令对我有用:
$ awk '{$1=$1}1' file.txt
这篇关于如何删除前导和尾随空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!