gpt4 book ai didi

bash - 在 bash 脚本中重定向输出时如何避免特殊字符

转载 作者:行者123 更新时间:2023-11-29 09:00:35 25 4
gpt4 key购买 nike

将输出从 bash 脚本重定向到文件时,我在文件中得到了特殊字符。例如,

for file in *; do echo $file; done > output.txt

然后如果我 cat output.txt

cat output.txt

我明白了

file1.txt
file2.txt
file3.txt
output.txt

但是在编辑文件时,我看到了这个:

^[[0m^[[0mfile1.txt
^[[0m^[[0mfile2.txt
^[[0m^[[0mfile3.txt
^[[0m^[[0moutput.txt

我如何避免那些讨厌的字符?


解决方法:

我在 .bashrc 中有以下行:

trap 'echo -ne "\e[0m"' DEBUG

通过删除它,我解决了问题。

谢谢大家的帮助。

最佳答案

这些是 ANSI 转义码,用于在终端中格式化文本。与其尝试删除它们,不如从一开始就阻止它们被写入。

你确定你是从你发布的确切代码中得到这个的吗?如果是这样,您的文件实际上在您的名称中包含这些字符,您应该简单地重命名它们。

看到这一点的更常见的方法是使用输出 ANSI 转义序列的工具。这是显示同一问题的可重现方式:

ls --color=always > file

如果您发布的代码是未经测试的示例,您应该仔细检查并找到负责 ANSI 代码的工具并使其停止(特别确保您没有循环 ls 输出)。

这是您遇到的问题的示例,touch 是某些进程/脚本的替代品,这些进程/脚本意外创建了带有 ANSI 转义的文件名:

# Reproduce the problem
$ touch $'\x1B[0m\x1B[0mfile.txt'

# Symptoms of the problem
$ ls *.txt
?[0m?[0mfile.txt

$ for f in *.txt; do echo "$f"; done
file.txt

$ for f in *.txt; do echo "$f"; done | cat -v
^[[0m^[[0mfile.txt

# Fix the problem by renaming the bad files
$ crud=$'\x1B[0m'; for f in *"$crud"*; do mv "$f" "${f//$crud/}"; done

# Now works as expected
$ ls *.txt
file.txt

$ for f in *.txt; do echo "$f"; done
file.txt

$ for f in *.txt; do echo "$f"; done | cat -v
file.txt

关于bash - 在 bash 脚本中重定向输出时如何避免特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23225064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com