user2094311
user2094311

Reputation:

csh script - Get substring or remove last character from string

I'm trying to write a shell script. In that I'm getting path as location from user. I want to find out out if it ends with '/' or not. If it does, I have to remove it and assign it to another variable.

Script I tried

#!/bin/csh

set loc="/home/user/"
if (("$loc" == */ ))
then
    echo true
    set b=${loc::-1}
    echo $b
else
    echo false
endif

But I'm not getting any output.

Upvotes: 1

Views: 12088

Answers (2)

David G.
David G.

Reputation: 690

First, I'm not positive, but I think you may have to use =~ instead of == for the test.

Second, csh, like classic Bourne shell, does not include string manipulation (beyond pasting). The classic tool for this is expr. So perhaps:

#!/bin/csh

set loc="/home/user/"
if (("$loc" =~ */ )) then
    echo true
    set b="` expr "$loc" : '\(.*\)/' `"
    echo $b
else
    echo false
endif

If you need to use expr for the test as well, you could rewrite the if as:

expr "$loc" : '.*/$' >/dev/null
if (( ! $? )) then

Additionally, expr has the same problems that test has, that parameters may be misinterpreted as commands. Thus, you wind up need to pad parameters with garbage and then strip it off again. like:

set b="` expr X"$loc"X : 'X\(.*\)/X' `"
set b="` expr substr X"$loc" 2 \( length X"$loc" - 2 \) `"

Overall, a bit painful. This is why shells developed there own math, comparison, and string slicing facilities to replace expr and test. On the other hand, this is much simpler (less costly) than building pipelines with echo, and awk, sed, or rev and cut.

Upvotes: 0

Mustafa DOGRU
Mustafa DOGRU

Reputation: 4112

try this;

#!/bin/csh
set loc="/home/user/"
set lastChar=`echo $loc | rev | cut -c -1`
if ( "$lastChar" == "/" ) then
    echo true
set b=`echo $loc | rev | cut -c 2- | rev`
#set b=`echo $loc | sed s'/.$//'`
#set b=`echo $loc | awk '{print substr($0, 1, length($0)-1)}'`
echo $b
else
    echo false
endif

Upvotes: 0

Related Questions