在第一个字母之后要删除额外的空格?
我们的文件包括:
Blue sky. Nice weather.
White cloud. Bright sun.
Cool air. Bla bla bla.
如何拥有这样的内容:
Blue sky. Nice weather.
White cloud. Bright sun.
Cool air. Bla bla bla.
这个命令awk '{$1=$1} 1' file
删除所有额外的空格。但是我们只需要在第一个字母之后去掉额外的空间。
有人知道吗?我们很感激你的关注!
发布于 2018-01-02 18:16:35
使用GNU awk,您可以:
awk '{match($0,/(^[ ]+)/,arr)}; {$1=$1;printf("%s%s\n", arr[1], $0)}'
match($0, /(^[ ]+)/, arr)
捕获行前导空间。$1=$1
删除所有前导空格和重复空格。printf("%s%s\n", a[1], $0)}
重新添加前导空格和打印.
发布于 2018-01-02 16:15:10
如果您运行的是Linux,并且具有GNU,您可以使用g
标志和一个数字到s
ub妓女命令:
sed -r 's/ +/ /g2' file.txt
引用info sed
的话:
Note: the POSIX standard does not specify what should happen when
you mix the `g' and NUMBER modifiers, and currently there is no
widely agreed upon meaning across `sed' implementations. For GNU
`sed', the interaction is defined to be: ignore matches before the
NUMBERth, and then match and replace all matches from the NUMBERth
on.
但是,由于在一种情况下,您确实希望在空格的第一个实例上进行替换(当没有前导空格时),所以完整的答案(用GNU Sed)是:
sed -r 's/^/ /;s/ +/ /g2;s/^ //' file.txt
换句话说,向所有行添加一个前导空间,然后“挤压”除第一个以外的连续空格的所有实例,然后删除添加的前导空间。
unexpand file.txt | sed 's/ */ /g' | expand
或者更简单地说:
unexpand file.txt | tr -s ' ' | expand
发布于 2018-01-02 18:13:46
在awk
中,这里有一种接吻的方法,我认为:
{tmp = substr($0,1,match($0,/[^ \t]/)-1); $1=$1; print tmp""$0}
例如。
$ awk '{tmp = substr($0,1,match($0,/[^ \t]/)-1); $1=$1; print tmp""$0}' file
Blue sky. Nice weather.
White cloud. Bright sun.
Cool air. Bla bla bla.
https://unix.stackexchange.com/questions/414390
复制相似问题