Grep在列表中给出文件时找不到文件

时间:2016-09-23 18:37:10

标签: bash grep

我有一个名为file_names_list.txt的文件,其中包含绝对文件名,例如,第一行是: ~/Projects/project/src/files/file.mm

我运行一个脚本来grep这些文件,

for file in $(cat file_names_list.txt); do 
        echo "doing file: $file"
        grep '[ \t]*if (.* = .*) {' $file | while read -r line ; do ... 

我得到了输出:

doing file: ~/Projects/project/src/files/file.mm
grep: ~/Projects/project/src/files/file.mm: No such file or directory

但是如果我去终端并输入

grep '[ \t]*if (.* = .*) {' ~/Projects/project/src/files/file.mm

我得到了正确的grep输出

这里的问题是什么?我没有想法

2 个答案:

答案 0 :(得分:0)

问题在于~字符。在bash中使用它时,该字符会扩展到您的主目录,但在这种情况下,它只是存储在变量$file中的另一个字符。要查看差异,请尝试以下方法:

file='~'
echo $file
echo ~

所以现在您必须重新创建文件file_names_list.txt或尝试修复它,例如与sed

sed -i -e "s|^~/|$HOME/|" file_names_list.txt

另请注意,最好使用while循环而不是for循环:

while IFS= read -r file; do
    # write your code here
done < file_names_list.txt

答案 1 :(得分:0)

您可以像这样使用脚本:

while IFS= read -r f; do
   grep '[ \t]*if .* = .* {' "${f/#\~/\$HOME}"
done < file_names_list.txt

由于~无法存储在变量中并且已展开,我们将在此BASH表达式的每一行中以~替换$HOME"${f/#\~/\$HOME}"