简体   繁体   中英

How to modify a file name within a shell script?

I am writing a shell script to sync to a github repo, kick off the build, then take the output file, rename it, and move it to a location where it can be seen by Apache.

It's the renaming of the file that I've got not the faintest how to do within a shell script (I have virtually no experience with shell scripts - my understanding

Compiler will create /var/espbuild/firstpart_1vXX_secondpart.bin

I need to move this file to:

/var/www/html/builds/espbuild/firstpart_1vXX_DATE_secondpart_postfix.bin

1vXX is the version number

DATE is the output of date +%m-%d

postfix is just a string.

I'm not really certain where to start for something like this - I'm sure there's a graceful way, since this is the kind of thing shell scripts are made for, but I know just about nothing about shell scripts.

Thanks in advance

You can get the result of a command into a variable by using $() :

DATE=$(date +%m-%d)

Then just use it in the new filename:

INPUT=/var/espbuild/firstpart_1vXX_secondpart.bin
OUTPUT=/var/www/html/builds/espbuild/firstpart_1vXX_${DATE}_secondpart_postfix.bin
mv ${INPUT} ${OUTPUT}

Edit: To get out the version part, here's a quick example:

VERSION=$(grep -o 1v.. <<< ${INPUT})

Then OUTPUT should be set like:

OUTPUT=/var/www/html/builds/espbuild/firstpart_${VERSION}_${DATE}_secondpart_postfix.bin

You can use this in BASH:

f='/var/espbuild/firstpart_1vXX_secondpart.bin'
s="${f##*/}"
s2=${s##*_}
dest="/var/www/html/builds/espbuild/${s%_*}_$(date '+%m-%d')_${s2%.*}_postfix.bin"

echo "$dest"
/var/www/html/builds/espbuild/firstpart_1vXX_07-14_secondpart_postfix.bin

cp "$f" "$dest"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM