Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy and replace content in string of file name

Tags:

bash

shell

I am trying to copy a file boot-1.5-SNAPSHOT.jar to boot-1.5.jar.

I've tried this using sed but I am getting an error. I know the syntax isn't right and I am hoping someone can complete it for me.

cp boot-* | sed -e 's:-SNAPSHOT::g'
cp: missing destination file operand after ‘boot-1.5-SNAPSHOT.jar’

The idea of this is that the script will not know the version number, just that the jar will be in the folder it's trying to copy the file from. Which is why I use an asterisk. The version number changes quite frequently so using cp file file2 will not work.

like image 227
user0000001 Avatar asked Feb 09 '23 20:02

user0000001


1 Answers

There is no need for sed, use Parameter Expansions:

$ file=boot-1.5-SNAPSHOT.jar
$ echo ${file/-SNAPSHOT/}
boot-1.5.jar

or

$ cp "$file" "${file/-SNAPSHOT/}"

In this case:

${parameter/pattern/string}

Pattern substitution. The pattern is expanded to produce a pattern just as in pathname expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string.

Note that since you are dealing with files, you should quote the variables (otherwise files with whitespace characters will mess things up).

Furthermore it is possible, that you should create a symbolic link instead of a copy:

$ ln -s "$file" "${file/-SNAPSHOT/}"
like image 55
Micha Wiedenmann Avatar answered Feb 19 '23 14:02

Micha Wiedenmann