【问题标题】:How to implement syntax highlighting using sed command in te gnome-terminal?如何在 te gnome-terminal 中使用 sed 命令实现语法高亮显示?
【发布时间】:2019-12-13 14:40:21
【问题描述】:

我想在 linux 终端上使用 sed 命令突出显示 C 程序的函数名称。

我可以使用 tput 为函数名称着色。我为此提供了下面的代码。 (第一行)

如果我使用 printf/echo/command 替换为终端的输出着色,我将无法着色。 (第二行代码)。我想这是因为我无法使用 \1 和 \2 引用字符串。使用它时,它会显示一些其他字符而不是函数名称。

我使用的正则表达式显示,函数名的第一个字符可以是字母或下划线,第二个字符可以是字母数字和下划线,第三个字符应该是一个左括号。我想通过使用 \1 \2 和 \3 来引用正则表达式,并对除 \3 之外的所有内容进行着色。这是我想出的主意。

我的问题是,有没有其他方法可以不为左括号着色或使用 printf 并为函数名称着色。

sed -E "s,([a-zA-Z_])([a-zA-Z0-9_]*)(\(),$(tput setaf 1)\1\2$(tput sgr0)\3," Sample.c

sed -E "s,([a-zA-Z_])([a-zA-Z0-9_]*)(\(),$(printf "\033[0;36m\1\2\033[0m\3")," Sample.c

示例 .c:

#include <stdio.h>
int main()
{
  int array[100], maximum, size, c, location = 1;
  printf("Enter the number of elements in array\n");
  scanf("%d", &size);
  printf("Enter %d integers\n", size);
  for (c = 0; c < size; c++)
    scanf("%d", &array[c]);
  return 0;
}

预期结果 -> main、printf、scanf 应该在 Sample.c 中着色。

【问题讨论】:

    标签: regex linux shell sed terminal


    【解决方案1】:

    tput 很聪明,但是对于嵌入式 printf,回溯无法解决,因为它位于子 shell 内,因此 printf 不起作用。

    var=$'ansi-ized content' 语法中有一个可能对您有用的 bashism。三个捕获组似乎没有必要。所以省略:

    BEGC=$'\033[0;36m' ENDC=$'\033[0m'; \
    sed -E "s,([a-zA-Z_][a-zA-Z0-9_]*)(\(),${BEGC}\1${ENDC}\2," Sample.c
    

    但是,还有一个更根本的问题是嵌套函数不会被突出显示。请注意,此处更新的 Sample.c 中虚构的“getSize()”函数不会突出显示:

    #include <stdio.h>
    int main()
    {
      int array[100], maximum, size, c, location = 1;
      printf("Enter the number of elements in array\n");
      scanf("%d", &size);
      printf("Enter %d integers\n", getSize(size));
      for (c = 0; c < size; c++)
        scanf("%d", &array[c]);
      return 0;
    }
    

    一个简单的正则表达式将无法工作,因为存在递归要求。可能 awk 可以做到,因为它有一个 while 循环和函数(gensub() 可能吗?)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-09
      • 1970-01-01
      • 2016-10-06
      • 1970-01-01
      相关资源
      最近更新 更多