Bash - 在 while 循环中使用 "find" 给出来自 DOS 文本文件的输入的空白结果
Bash - Using "find" in while loop is giving blank results with input from DOS text file
我有一个包含文件名列表但没有文件夹路径或扩展名的文本文件。我想遍历这个文件并找到与文件名匹配的路径。但是,我在 while 循环中的 find 命令没有给出结果。当我将它从 while 循环中取出时,find 命令起作用。
这是我的示例输入文件 (input.txt):
12345
56789
...
09987
89008
实际文件是这样存储的:
/home/user/path/to/file/12345.jpg
这是我的脚本 (find_files.sh):
#!/bin/bash
while IFS= read -r line || [[ -n "$line" ]]; do
echo $line
file=$(find /home/engage/ -name "${line}*" -print)
echo $file
done < ""
我用以下方式调用它:
./find_files.sh input.txt
我得到的输出是这样的:
12345
56789
...
09987
89008
所以 find
没有得到任何结果。我究竟做错了什么?谢谢!
您的输入文件具有 Windows 样式的 \r\n
行结尾,意外的 \r
导致匹配失败。
使用 dos2unix
、fromdos
或 tr -d '\r' < input.txt > fixed_input.txt
从您的输入文件中删除它们。
您也可以使用 line=${line%$'\r'}
在循环中的 运行 时间剥离它们
我有一个包含文件名列表但没有文件夹路径或扩展名的文本文件。我想遍历这个文件并找到与文件名匹配的路径。但是,我在 while 循环中的 find 命令没有给出结果。当我将它从 while 循环中取出时,find 命令起作用。
这是我的示例输入文件 (input.txt):
12345
56789
...
09987
89008
实际文件是这样存储的:
/home/user/path/to/file/12345.jpg
这是我的脚本 (find_files.sh):
#!/bin/bash
while IFS= read -r line || [[ -n "$line" ]]; do
echo $line
file=$(find /home/engage/ -name "${line}*" -print)
echo $file
done < ""
我用以下方式调用它:
./find_files.sh input.txt
我得到的输出是这样的:
12345
56789
...
09987
89008
所以 find
没有得到任何结果。我究竟做错了什么?谢谢!
您的输入文件具有 Windows 样式的 \r\n
行结尾,意外的 \r
导致匹配失败。
使用 dos2unix
、fromdos
或 tr -d '\r' < input.txt > fixed_input.txt
从您的输入文件中删除它们。
您也可以使用 line=${line%$'\r'}