drdot
drdot

Reputation: 3347

How to use bash parameter substitution to remove "./"?

I am writing a bash script to change a string

./FirstJavaProgram.class

to

FirstJavaProgram

I came up with this script. However bash complains line 4 is bad substitution.

#!/bin/sh
file=${1%%.class}
echo $file
file=${file/.\//}

How should I write the correct syntax?

Upvotes: 2

Views: 200

Answers (2)

Charles Duffy
Charles Duffy

Reputation: 295500

${var//search/replace} is a bash-only feature. It is not guaranteed to be present with /bin/sh. Use ${var#prefix} instead, which is part of the POSIX sh specification and so guaranteed to be offered by /bin/sh.

#!/bin/sh
file=${1%.class}
echo "Trimmed suffix:      $file"
file=${file#./}
echo "Also trimmed prefix: $file"

...if the parameter is ./FirstJavaProgram.class, the output will be:

Trimmed suffix:      ./FirstJavaProgram
Also trimmed prefix: FirstJavaProgram

By contrast, if you want to use bash-only features, start your script with #!/usr/bin/bash, or #!/bin/bash, #!/usr/bin/env bash, etc. as appropriate.

Upvotes: 1

Mikołaj Głodziak
Mikołaj Głodziak

Reputation: 5277

Try this command: echo "./FirstJavaProgram.class" | sed 's\[.]/\\'

Your script should be look like:

#!/bin/sh
file=./FirstJavaProgram.class
echo $file 
echo $file | sed 's\[.]/\\'

Upvotes: 0

Related Questions