bash - 从字符串中去除前导和尾随 ansi/tput 代码
问题描述
此处的应用程序正在“清理”字符串以包含在日志文件中。为了论证起见,我们假设 1) 在运行时对字符串进行着色是正确的;2)我需要屏幕上的前导和尾随空格,但从日志中删除了多余的空格。
此处的特定应用程序是生成日志文件。不是所有的行都会被着色,也不是所有的行都会有前导/尾随空格。
鉴于此,我想
- 删除设置颜色和重置的所有代码。原因一会就明白了
- 删除前导和尾随空格
当您(在任何地方)搜索如何在 bash 中去除颜色代码时,您可以找到许多不同的方法来完成它。然而,到目前为止,我发现似乎没有人解决尾随重置问题。$(tput sgr0)。在我看到的示例中,这是无关紧要的,但是我对去除前导/尾随空格的额外要求使其复杂化/使其成为一项要求。
这是我演示该问题的示例脚本:
#!/bin/bash
# Create a string with color, leading spaces, trailing spaces, and a reset
REPLY="$(tput setaf 2) This is green $(tput sgr0)"
echo "Colored output: $REPLY"
# Remove initial color code
REPLY="$(echo "$REPLY" | sed 's,\x1B\[[0-9;]*[a-zA-Z],,g')"
echo "De-colorized output: $REPLY"
# Remove leading and trailing spaces if present
REPLY="$(printf "%s" "${REPLY#"${REPLY%%[![:space:]]*}"}" | sed -n -e 'l')"
echo "Leading spaces removed: $REPLY"
REPLY="$(printf "%s" "${REPLY%"${REPLY##*[![:space:]]}"}" | sed -n -e 'l')"
echo "Trailing spaces removed: $REPLY"
输出是(不知道如何在这里给文本着色,假设第一行是绿色,后面的行不是):
我愿意看到我的方式的错误,但在尝试不同的东西大约三个小时后,我很确定我的 google-fu 让我失望了。
感谢您的任何帮助。
解决方案
这对我有用:
$ REPLY="$(tput setaf 2) This is green $(tput sgr0)"
$ echo -n $REPLY | od -vAn -tcx1
033 [ 3 2 m T h i s
1b 5b 33 32 6d 20 20 20 20 20 20 20 54 68 69 73
i s g r e e n
20 69 73 20 67 72 65 65 6e 20 20 20 20 20 20 20
033 [ m 017
20 1b 5b 6d 0f
$ REPLY=$(echo $REPLY | sed -r 's,\x1B[\[\(][0-9;]*[a-zA-Z]\s*(.*)\x1B[\[\(].*,\1,g' | sed 's/\s*$//')
$ echo -n $REPLY | od -vAn -tcx1
T h i s i s g r e e n
54 68 69 73 20 69 73 20 67 72 65 65 6e
显然sed
不支持非贪婪正则表达式,这将消除第二个正则表达式。
编辑:这个应该适用于您的输入:
$ REPLY="$(tput setaf 2) This is green "$'\x1B'"(B$(tput sgr0)"
$ echo -n $REPLY | od -vAn -tcx1
033 [ 3 2 m T h i s
1b 5b 33 32 6d 20 20 20 20 20 20 20 54 68 69 73
i s g r e e n
20 69 73 20 67 72 65 65 6e 20 20 20 20 20 20 20
033 ( B 033 [ m 017
20 1b 28 42 1b 5b 6d 0f
$ REPLY=$(echo "$REPLY" | sed -r -e 's,\x1B[\[\(][0-9;]*[a-zA-Z]\s*([^\x1B]+)\s+\x1B.*,\1,g' -e 's,\s*$,,')
$ echo -n $REPLY | od -vAn -tcx1
T h i s i s g r e e n
54 68 69 73 20 69 73 20 67 72 65 65 6e
与 bash 替换相比,我发现 sed 不那么神秘(或者像正则表达式一样不那么神秘)。但这只是我:)
推荐阅读
- python - 为什么我的 pyinstaller python 程序在双击而不是在 cmd 运行时崩溃
- javascript - 如何从 framework7 中的页面访问 my-app.js?
- netsuite - NetSuite 保存的搜索结果为空白
- java - 将外部属性添加到 OntModel
- flutter - Flutter 在 ListTile 中显示 sql 数据而不是 DataCell
- c++ - 带有构造函数的 C++ 枚举类
- wpf - 上下文菜单在命令执行期间保持可见
- c# - 确定部署在具有多个 .net 框架版本的 IIS 服务器中的 Web 应用程序的 Asp.net 版本
- json - 如何让 jq 保留 bigint 值?
- javascript - 如何将 Jquery 代码转换为 GithubPages 的 Javascript