问题
I'm trying to use the following to locate a file then copy the first result to the directory that is set by $dir. It works fine when I don't set a variable and use an absolute path, but that's not what I need.
This doesn't work:
dir="/path/to/destination/";
mkdir "$dir";
locate -l 1 target_file.txt | awk '{print "cp " $1 $dir " "}' | sh
error message is:
awk: illegal field $(), name "dir"
input record number 1, file
source line number 1
cp: fts_open: No such file or directory
This works:
locate -l 1 target_file.txt | awk '{print "cp " $1 " /path/to/destination/"}' | sh
回答1:
Inside an awk
script, you don't use $
to prefix variables; you use it to refer to fields in the line of input.
dir="/path/to/destination/";
mkdir "$dir";
locate -l 1 target_file.txt | awk -v dir="$dir" '{print "cp", $1, dir}' | sh
This will work OK as long as you have no spaces in your names.
dir="/path/to/destination/";
mkdir "$dir";
locate -l 1 target_file.txt | awk -v dir="$dir" '{printf "cp \"%s\" \"%s\"\n", $1, dir}' | sh
Unless I screwed up the backslashes, that should work with spaces etc in file names. The whole pipeline will be screwed up if someone is unkind enough to put a newline into a file name.
来源:https://stackoverflow.com/questions/13943713/bash-locate-file-awk-copy-not-working-correctly