[英]How to use awk to do file copy. Copy using split in awk not working
I am missing something subtle. 我错过了一些微妙的东西。 I tried running below command but it didn't work.
我尝试在命令下运行,但它没有用。 Can you please help .
你能帮忙吗?
ls | awk '{ split($1,a,".gz")} {cp " " $1 " " a[1]".gz"}'
Although when i am trying to print it is showing copy command. 虽然我正在尝试打印时显示复制命令。
ls | awk '{ split($1,a,".gz")} {print "cp" " " $1 " " a[1]".gz"}'
Not sure where the problem is. 不确定问题出在哪里。 Any pointers will be helpful
任何指针都会有所帮助
To summarize some of the comments and point out what's wrong with the first example: 总结一些评论并指出第一个例子有什么问题:
ls | awk '{ split($1,a,".gz")} {cp " " $1 " " a[1]".gz"}'
^ unassigned variable
The cp
defaults to "" and is not treated as the program cp
. cp
默认为“”,不被视为程序cp
。 If you do the following in a directory with one file, test.gz_monkey
, you'll see why: 如果在包含一个文件
test.gz_monkey
的目录中执行以下test.gz_monkey
,您将看到原因:
ls | awk '{split($1,a,".gz"); cmd=cp " " $1 " " a[1] ".gz"; print ">>" cmd "<<" }'
results in 结果是
>> test.gz_monkey test.gz<<
^ the space here is because cp was "" when cmd was assigned
Notice that you can separate statements with a ;
请注意,您可以将语句与
;
instead of having two action blocks. 而不是有两个动作块。 Awk does support running commands in a subshell - one of which is
system
, another is getline
. awk确实支持在子shell中运行命令 - 其中一个是
system
,另一个是getline
。 With the following changes, your concept can work: 通过以下更改,您的概念可以正常工作:
ls | awk '{split($1,a,".gz"); cmd="cp "$1" "a[1]".gz"; system(cmd) }'
^ notice cp has moved inside a string
Another thing to notice - ls
isn't a good choice for only finding files in the current directory. 另一件需要注意的事情 -
ls
不是仅在当前目录中查找文件的好选择。 Instead, try find
: 相反,尝试
find
:
find . -type f -name "*.gz_*" | awk '{split($1,a,".gz"); cmd="cp "$1" "a[1]".gz"; system(cmd) }'
while personally, I think something like the following is more readable: 虽然我个人认为以下内容更具可读性:
find . -type f -name "*.gz_*" | awk '{split($1,a,".gz"); system(sprintf( "cp %s %s.gz", $1, a[1])) }'
Why are you using awk
at all? 你为什么一直使用
awk
? Try: 尝试:
for f in *; do cp "$f" "${f%.gz*}.gz"; done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.