Skip to content

Instantly share code, notes, and snippets.

@oneamtu
Created February 15, 2013 22:27
Show Gist options
  • Save oneamtu/4964096 to your computer and use it in GitHub Desktop.
Save oneamtu/4964096 to your computer and use it in GitHub Desktop.
A simple script to copy a file with a path matching a pattern and then optionally replace that pattern with a different string in the file name
#!/usr/bin/awk -f
# A simple script to copy a file with a path matching a pattern
# and then optionally replace that pattern with a different string
# in the file name
#
# Usage: ./cp_and_rename.awk -v subject=[foo] -v replacement=[bar] \
# -v dest_prefix=[baz]
#
# E.g.
# for an existing file
# awesome/foo.awk
#
# find . | ~/apps/bin/cp_and_rename.awk -v subject=foo -v replacement=bar \
# -v dest_prefix=baz -v dry_run=true
#
# the effect is
#
# mkdir -p baz/awesome
# cp -r awesome/foo.awk baz/awesome/bar.awk
#
# Add -v dry_run=true to make the script only output the commands without
# actually running them
#
# All the arguments are optional (with different effects)
#
# If you want to just check some file path strings manually to see the effects
# you can just call the script
#
# ~/apps/bin/cp_and_rename.awk -v subject=foo -v replacement=bar \
# -v dest_prefix=baz -v dry_run=true
#
# and then enter the string with STDIN
#
# @author 2013 Octavian Neamtu
$0 ~ subject {
subject_file_path=$0
subs_file_path=$0
sub(subject, replacement, subs_file_path)
if (dest_prefix != "") {
dest_file_path=sprintf("%s/%s", dest_prefix, subs_file_path);
} else {
dest_file_path=subs_file_path;
}
match(dest_file_path, "^.*/")
dest_dir=substr(dest_file_path, 1, RLENGTH-1)
mkdir_cmd=sprintf("mkdir -p %s", dest_dir)
if (dry_run == "") {
system(mkdir_cmd)
close(mkdir_cmd)
}
print(mkdir_cmd)
cp_cmd=sprintf("cp -r %s %s", subject_file_path, dest_file_path)
if (dry_run == "") {
system(cp_cmd)
close(cp_cmd)
}
print(cp_cmd)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment