سؤال

I am working on a bash script that should find files such as

/var/www/templates/testdoctype/test_file.html.head

and return something like

cp -f '/var/www/sites/t/test/test_file.html' '/home/user/tmp/test_file.html'    

my script so far looks like this:

#!/bin/bash
DOCPATH='/var/www/templates/testdoctype'
INSTALL_PATH='/var/www/sites/t/test'
PKGBACKPATH='/home/user/tmp'

function find_suffix_head {
  find "$FROM/$DOCTYPE" -type f -iname "*.head" -print \
  | awk -v docpath="$DOCPATH" -v installpath="$INSTALL_PATH" -v pkgbackpath="$PKGBACKPATH" \
  '{ sub( docpath, installpath ) sub(/.head$/, "") } { printf "cp -f ""'\''"$0"'\''"" " ; sub( installpath, pkgbackpath ) ; print "'\''"$0"'\''" }'
}

find_suffix_head

This returns

cp -f '/var/www/templates/testdoctype/test_file.html' '/var/www/templates/testdoctype/test_file.html'

So, sub(/.head$/, "") works as it should, but sub( docpath, installpath ) and sub( installpath, pkgbackpath ) does not.

هل كانت مفيدة؟

المحلول

No need for awk, you can do it with bash:

function find_suffix_head {
  find "$FROM/$DOCTYPE" -type f -name "*.head" | while read filename; do
    filename=${filename%.head} # strip suffix
    filename=${filename#/var/www/templates/testdoctype} # strip prefix
    echo cp -f "$INSTALL_PATH/$filename" "$PKGBACKPATH/$filename"
  done
}

From there you can just run the cp, too, rather than echoing it.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top