How do I escape the output of grep so that bash can read the file names correctly?
I have a text file that is the output of a find command. For each line, I want to make a symlink. For now, I'm just testing my loop with ls
. However, I am not quoting the string output of grep properly for special characters. This causes filesystem commands on each file to fail.
$ tree dir/
dir/
├── Another & file ' name.txt
└── file name.txt
0 directories, 2 files
$ cat files.txt
dir
dir/Another & file ' name.txt
dir/file name.txt
$ grep file files.txt | awk -v q='"' '{printf(q"%s"q"\n", $0);}'
"dir/Another & file ' name.txt"
"dir/file name.txt"
$ while read p ; do
echo $p; ls $(grep file files.txt | awk -v q='"' '{printf(q"%s"q"\n", $0);}') ;
done < files.txt
dir
ls: cannot access '"dir/Another': No such file or directory
ls: cannot access '&': No such file or directory
ls: cannot access 'file': No such file or directory
...
dir/Another & file ' name.txt
ls: cannot access '"dir/Another': No such file or directory
ls: cannot access '&': No such file or directory
ls: cannot access 'file': No such file or directory
...
I've tried both single quotes and double quotes. How can I escape this to execute commands on the paths outputted from grep?
files.txt
one-by-one, and then grepping the lines out of the same file again? Do you want to find duplicates or partial matches from the file, ...? If you just want to do something with every file (line) matching the grep, would just something like this work:grep file files.txt | while read p ; do echo "<$p>" ; ln -s "$p" make-links-here/ ; done
– ilkkachu Jul 28 '16 at 08:48