regex - 如何在 te gnome-terminal 中使用 sed 命令实现语法高亮?

标签 regex linux shell sed terminal

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

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

如果我使用 printf/echo/命令替换为终端的输出着色,我将无法进行着色。 (第二行代码)。我想这是因为我无法用\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 中着色。

最佳答案

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()?)

关于regex - 如何在 te gnome-terminal 中使用 sed 命令实现语法高亮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57369336/

相关文章:

regex - 从 OCR 图像文件中提取文本

iphone - 如何在iOS中使用正则表达式获取匹配项?

linux - Apache 虚拟主机的问题

Linux 静态驱动加载问题

ubuntu 服务器上的 Mysql 自动备份

linux - lsof linux 命令使用参数值计算正在运行的实例

javascript - 如何创建正则表达式以不只接受特殊字符或数字

c - linux c程序中函数strcpy的奇怪段错误

bash - 从 Bash shell 将文本转换为字节?

regex - str_extract_all 返回不匹配的组