如何删除单词之间的多个空格?

如何删除单词之间的多个空格?
grep include /etc/nginx/nginx.conf

输出:

include /etc/nginx/modules-enabled/*.conf;
    include             mime.types;
        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;

期望的输出:

include /etc/nginx/modules-enabled/*.conf;
include mime.types;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;

答案1

awk '/include/ {$1 = $1; print}' < your-file

会那么做。

通过将某些内容分配给$1,强制awk通过将字段(默认情况下由空格分隔(至少是空格和制表符,可能其他取决于语言环境和 awk 实现))与OFS(默认情况下为空格)来重建记录。

等价sed的:

sed -E '/include/!d; s/[[:space:]]+/ /g; s/^ //; s/ $//' < your-file

[[:space:]][[:blank:]]其中至少包括空格和制表符;[[:space:]]还包括垂直间距字符 1,如果文件具有 MSDOS CRLF 行结尾,这在这里可能很有用,因为它会删除行末尾的那些虚假 CR。


1 例如垂直制表符、换页符(不应出现在输入中)、换行符、行分隔符(不会出现在记录awk进程中awk内容每个线反过来

答案2

使用 sed 应该可以简单地做到这一点:

% sed -e 's/^ *//g' -e 's/  */ /g' file.txt
include /etc/nginx/modules-enabled/*.conf;
include mime.types;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;

s/pattern/replacement/进行查找和替换,^意味着行的开头,*任意数量的空格,并且*只是一个空格后跟任意数量的空格。最后的g代表“全局”,即替换所有匹配项。

[[:space:]]如果那里还有选项卡,请将空格替换为:

% sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]][[:space:]]*/ /g' file.txt

答案3

如果你可以使用 Perl:

#!/usr/bin/perl
use v5.30;
use warnings;

while (<DATA>){
    $_ =~ s/[[:blank:]]/ /g; #replace any number of subsequent space with single space except newline
    $_ =~ s/\s//; #remove single space at the beginning of each line
    print("$_");
}
__DATA__
include /etc/nginx/modules-enabled/*.conf;
    include             mime.types;
        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;

如果您想从命令行尝试单行版本:

perl -nE '{$_ =~ s/[[:blank:]]+/ /g; $_ =~s/^\s//; print $_}' file.txt

答案4

grep include /etc/nginx/nginx.conf | awk -F ' ' '{print $2}' | sort | uniq

相关内容