Bash — locate file, awk copy not working correctly

大兔子大兔子 提交于 2019-12-24 13:47:03

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!