1

I am trying to copy the files not present in one directory to the other directory by using awk

diff -r dir1 dir2 | grep dir1 | awk '{$1=$2=$3 =""; print "cp \"./dir1/" substr($0,4) "\" ./dir2/"}' | sh

This works fine except that I also want to print the file that is being copied. Something like cp ./dir1/file1.txt ./dir2/ on stdout

How do I do this. I know it's simple but I can't figure it out. I tried tee and echo commands but in vain.

2

You could use |sh -x. From man page:

 -x xtrace
         Write each command (preceded by the value of the PS4 variable
         subjected to parameter expansion and arithmetic expansion) to
         standard error before it is executed.  Useful for debugging.

So shell will print to stderr all command executed. And you could use stderr redirection, like |sh -x 2>commands_list.txt to get list of command in separate file.

  • 1
    Great for seeing what a script is doing. But if you use a single command to copy a bunch of files, for example cp *.txt newfolder/ this would only print the single command, not each file being copied. – Xen2050 Nov 27 '16 at 23:42
1

cp can tell you what it's doing too, it's option

-v, --verbose
          explain what is being done

prints to stdout what files are copied where, in the form:

‘file1’ -> ‘file2’
  • Yeah. This is so simple. Now i feel I have asked a stupid question. – Rohit Walavalkar Nov 20 '16 at 8:56
  • 1
    Nah, good question. Most programs have a verbose or -v option to give more info on what they're doing, some (ex. gpg) will accept several v's for more "verbosity", always check the man page first (or sometimes info page, more info if it's different). I'll bet awk probably has a simple way to send a copy to stdout too but I'm not too current on it right now – Xen2050 Nov 27 '16 at 23:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.