LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Shell script to copy file name with part of directory (https://www.linuxquestions.org/questions/linux-general-1/shell-script-to-copy-file-name-with-part-of-directory-279419/)

Transition 01-18-2005 03:53 PM

Shell script to copy file name with part of directory
 
Here's the situation. I need to figure out who to take a file from a directory and automatically copy it as follows..

For example if i had a file in this directory

/usr/local/backups/db/01.18.05.Tuesday.gz

the desired result would be to copy this file into a new directory such as /copy with the name db.01.18.05.Tuesday.gz. So in addition to copying i need to strip off the directory name it's in and append it to the beginning of the file.

:confused:

Any help is greatly appreciated.

Dark_Helmet 01-18-2005 04:06 PM

It ain't pretty, but:
Code:

echo "/usr/local/backups/db/01.18.05.Tuesday.gz" | sed 's@.*/\([^/]\+/[^/]\+\)@\1@' | sed 's@/@.@'
That turns the full path of the filename into the filename you wanted. Just run it and you'll see :)

There might be a much more elegant solution using basename and dirname, but I like sed, and the command above works (if a bit cryptic).

EDIT:
Actually, that command will break if the file is stored in the root (/) directory, or a relative directory with only one slash in the path. Just fyi.

ilikejam 01-18-2005 05:05 PM

cp "$FILE" /copy/db.`basename "$FILE"`

should do the trick. e.g.:
cp /home/dave/hello.txt /copy/db.`basename /home/dave/hello.txt`

Dave

Transition 01-18-2005 05:14 PM

Quote:

Originally posted by ilikejam
cp "$FILE" /copy/db.`basename "$FILE"`

should do the trick. e.g.:
cp /home/dave/hello.txt /copy/db.`basename /home/dave/hello.txt`

Dave

That doesnt append the directory name to the file though. I end up with a file called db.hello.txt instead of the desired dave.hello.txt.

Transition 01-18-2005 05:33 PM

Got it.

cp /home/dave/hello.txt /copy/`basename /home/dave/`.hello.txt

Thanks ilikejam & DarkHelmet. :)

ilikejam 01-18-2005 05:40 PM

Code:

#!/bin/bash

FILE="</full/path/to/file.gz>"

DIRNAME=`dirname "$FILE"`
PREFIX=`basename "$DIRNAME"`
BASENAME=`basename "$FILE"`

cp "$FILE" /copy/"$PREFIX"."$BASENAME"

That should do it.


All times are GMT -5. The time now is 04:28 PM.