问题描述
我尝试使用以下方法来查找文件,然后在第一个结果复制到被$ DIR设置的目录。当我没有设定一个变量,使用绝对路径,但是这不是我所需要的正常工作。
这不工作:
DIR =/路径/要/目的/;
MKDIR$目录;
找到-l 1 target_file.txt | AWK'{打印CP$ 1 $目录}'| SH
错误消息是:
AWK:非法场$(),名称为DIR
输入记录号1,文件
源代码行数1
CP:fts_open:没有这样的文件或目录
这工作:
定位-l 1 target_file.txt | AWK'{打印CP$ 1/路径/要/目的/}'| SH
里面的 AWK
脚本,您不使用 $
至preFIX变量;你用它来指在输入行领域。
DIR =/路径/要/目的/;
MKDIR$目录;
找到-l 1 target_file.txt | AWK -v DIR =$目录'{打印CP,$ 1,DIR}| SH
你有没有空格在你的名字这只要工作确定。
DIR =/路径/要/目的/;
MKDIR$目录;
找到-l 1 target_file.txt | AWK -v DIR =$目录'{printf的CP \\%s \\的\\%s \\的\\ n,$ 1,DIR}| SH
除非我搞砸了反斜线,应在文件名称中的空格等工作。整个管道将被搞砸了,如果有人不友善足以把一个换行符到一个文件名。
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
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.
这篇关于巴什 - 查找文件时,awk复制无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!