I am trying to grep a word on all the files from the list.txt
.
list.txt:
$HOME/a.txt
$HOME/b.txt
$HOME/c.txt
When I use
grep -i 'word' $(cat list.txt)
it doesn't realize $HOME
. But the following command works!
grep 'word' $HOME/a.txt
CodePudding user response:
You will need a little bit of magic from envsubst
:
$ grep word $(cat list.txt | envsubst)
...
CodePudding user response:
- Use
envsubst
to replace$HOME
with the actual directory name (assuming it doesn't contain spaces) - Use
xargs
to honor quotes and backslashes (so filenames with spaces can still be represented) while splitting the list of filenames on envsubst's stdout into command line arguments passed togrep
envsubst <file.txt | xargs grep -e word
CodePudding user response:
This looks like both bash and ksh question so I'll answer accordingly.
What's going on is the $HOME is interpreted by the shell, not grep. You need to interpret $HOME before passing it to grep. The eval keyword can do that for you in something like this:
for file in $(cat test.txt )
do
eval "grep 'word' $file"
done
If you use the cat directly, the resulting string contains the newlines. To avoid that, I put the files into an array and used the array in (the < can be used in place of cat). This also works:
typeset -a test=( $( < test.txt ) )
eval "grep word ${test[@]}"