且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

python,从目录中读取文件名,在bash脚本中使用字符串

更新时间:2023-02-23 18:41:36

问题中的Python脚本无法完成Bash本身无法完成的所有工作,并且变得越来越简单.改用简单的本机Bash:

The Python script in the question doesn't do anything that Bash cannot already do all by itself, and simpler and easier. Use simple native Bash instead:

shopt -s nullglob
for path in /home/testfiles/*; do
    if [[ -f "$path" ]]; then
        filename=$(basename "$path")
        echo "do something with $filename"
    fi
done

如果Python脚本的功能超出了您在问题中所写的内容,例如,它执行一些复杂的计算并吐出文件名,在Bash中做起来会很复杂,那么您确实有一个合法的用例来保留它.在这种情况下,您可以像这样遍历输出中的行:

If the Python script does something more than what you wrote in the question, for example it does some complex computation and spits out filenames, which would be complicated to do in Bash, then you do have a legitimate use case to keep it. In that case, you can iterate over the lines in the output like this:

python read_files.py | while read -r filename; do
    echo "do something with $filename"
done