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
. If you do the following in a directory with one file, test.gz_monkey
, you'll see why:
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
. 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. Instead, try 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])) }'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With