如何用一个空格替换多个空格并使用awk快速保持开头和结尾的所有空白?

时间:2017-04-08 05:22:53

标签: awk

输入字符串

"   x1    x2    x3       x4   "

预期字符串

"   x1 x2 x3 x4   "

用一个空白替换多个空白,并用awk保持所有空白在开头和结尾。

这是我的尝试。

echo "   x1    x2    x3       x4   " |awk 'BEGIN{FS=" "}{$1=$1;print $0}'

所有多个空白都用一个空白重新填充,但是开头和结尾的所有空白也都被删除了 如何用awk快速转换字符串?
1.用一个空白替换多个空白
2.保持所有空白的开头和结尾

sed's / \ b + \ b / / g'可以解决问题。

echo "   x1    x2    x3       x4   " | sed 's/\b \+\b/ /g'

说清楚。

echo "|$(echo "   x1    x2    x3       x4   " | sed 's/\b \+\b/ /g')|"
|   x1 x2 x3 x4   |

reg表达式/ \ b + \ b /不能在awk中使用。

echo "   x1    x2    x3       x4   " | awk '{gsub(/\b \+\b/," ");print}'
echo "   x1    x2    x3       x4   " | awk '{gsub(/\b +\b/," ");print}'

3 个答案:

答案 0 :(得分:1)

@try:

awk '{match($0,/^\" +/);val1=substr($0,RSTART,RLENGTH);match($0,/ +\"$/);val2=substr($0,RSTART,RLENGTH);gsub(/[[:space:]]+/,FS);gsub(/\" /,val1);gsub(/ \"$/,val2);print}'  Input_file

也会很快添加代码说明。

修改

awk '{
        match($0,/^\" +/);              #### Using match keyword for finding the starting " till first space.
        val1=substr($0,RSTART,RLENGTH); #### creating val1 variable and saving that above match's value into it(where RSTART and RLENGTH are awk's default variable which will be set only when a match is found.)
        match($0,/ +\"$/);              #### Using match keyword for finding the space till string " end of the line.
        val2=substr($0,RSTART,RLENGTH); #### creating val2 variable and saving that above match's value into it(where RSTART and RLENGTH are awk's default variable which will be set only when a match is found.)
        gsub(/[[:space:]]+/,FS);        #### global substitution of space for whole spaces with a single space in complete record/line.
        gsub(/\" /,val1);               #### Now substituting the match of starting with " till space with variable val1.
        gsub(/ \"$/,val2);              #### Now substituting the match of starting with " till space with variable val2.
        print                           #### print the current line.
     }
    '  Input_file                       #### Mentioning Input_file here.

答案 1 :(得分:1)

我们只需要使用正确的标识符:

echo "|$(echo "   x1    x2    x3       x4   " | awk 'gsub(/\y +\y/," ")')|"

我输入额外的回声只是为了显示还有其他空格

答案 2 :(得分:0)

对于圣杯的答案。

sudo apt-get install gawk
echo "   x1    x2    x3       x4   " | awk 'gsub(/\y +\y/," ")'

使用以下内容更清楚。

echo "|$(echo "   x1    x2    x3       x4   " | awk 'gsub(/\y +\y/," ")')|"