在for循环中迭代时,sed无法读取可执行文件

问题描述 投票:-2回答:1

[在终端外壳中,我试图遍历一组Python文件并执行sed的查找和替换,例如:

$ for f in `ls *.py`; do sed -i 's|foo|bar|g' $f; done;

但是,对于某些文件(特别是那些我已更改为可执行的Python脚本),它会显示错误:

sed: can't read example_script.py: No such file or directory

为什么它不适用于可执行文件,但不适用于其他文件?

bash sed ls
1个回答
0
投票

之所以无法通过sed读取可执行文件,是因为我将ls别名为ls --color=auto。因此,ls在for循环中返回的文件名不仅是带有文件名的ascii字符串,而且还包含颜色信息,例如:]

''$'\033''[01;32mexample_script.py'$'\033''[0m'

所以sed找不到这个奇怪的文件!

对我来说(鉴于已设置此别名的解决方案是改为运行我的for循环,确保指定ls --color=none,即:]

for f in `ls --color=none *.py`; do
  sed -i 's|foo|bar|g' $f;
done;

编辑:如评论中所指出,在这种情况下,实际上不需要使用ls创建我的可迭代列表,而我可以做:]]

for f in *.py; do
  sed -i 's|foo|bar|g' $f;
done;
© www.soinside.com 2019 - 2024. All rights reserved.