Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use awk to do file copy. Copy using split in awk not working

Tags:

unix

awk

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

like image 294
user3341078 Avatar asked Dec 25 '22 12:12

user3341078


1 Answers

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])) }'
like image 195
n0741337 Avatar answered Dec 31 '22 14:12

n0741337