sed替换-空格按制表符

时间:2020-09-17 11:15:12

标签: bash shell sed

我正在尝试通过Shell脚本中的sed命令格式化一批.c文件,以正确对齐函数名称。我将int(space)function1()替换为int(3tab)function1()

int         function1(int foo)
{
    *my_function_code*
}

char        function2(int foo)
{
    *my_function_code*
}

int         main(int foo)
{
    *my_function_code*
}

我实际上正在使用以下循环来应用替换:

#align global scope
printf " Correct global scope alignement...\n"
for file in ${FILES[@]}; do
sed -i -e 's/^int */int         /g' \
    -i -e 's/^char */char       /g' \
    -i -e 's/^float */float     /g' \
    -i -e 's/^long int */long int   /g' ${file}
done

问题是,如果我重新运行脚本,而不是什么也不做,它将再次添加多个选项卡。给我这个:

int                     function1(int foo)
{
    *my_function_code*
}

char                    function2(int foo)
{
    *my_function_code*
}

int                     main(int foo)
{
    *my_function_code*
}

*不应只查找空格而不是制表符,还是应该将其视为所有空白字符?

1 个答案:

答案 0 :(得分:3)

请您尝试按照所示样本进行以下操作,编写和测试。只需检查行是否从intchar开始(您也可以在条件中添加float和long int),然后在此处在3个标签中替换空格。

sed -E '/^int|^char/s/ +/\t\t\t/'  Input_file
相关问题