Using sed inside system call in awk

HI ,
I am trying to write a code where if a file system has / at the end then replace it with null but it should not affect root file system /

for example if
ip is /var/opt/home/ then o/p is /var/opt/home
but if ip is / then it should remain /.

for this i am using below code but no success

echo "hi/" |awk -F "/" -v line=$0 '{ if ($NF == "" && NF -eq 2 && $1 == "") print $0;else print system("echo " $line \"| (sed 's>/$>>')\");}'

I am getting error:

I have tried numerous combinations but no luck.

thanks for help

Jcpratap

That method is quite an overkill by the looks of it. You could simply do something like this (providing you have an bash/ksh that supports this form of parameter expansion):

fs="/one/two/three/"
tmp=${fs%/}
echo ${tmp:-/} # The expected result

I imagine there are even smarter ways to.

Hello Jcpratap,

It seems a very heavy way to achieve this. Could you do something based on the following instead?

my_dir="hi/"
my_dir="${my_dir%/:=/}"
echo $my_dir

By way of explanation, the variable is substituted for a value based on itself. It could be done in two steps for more clarity like this:-

my_dir="hi/"
my_dir="${my_dir%/}"        # 1st substitution
my_dir="${my_dir:=/}"       # 2nd substitution
echo $my_dir

The first substitution trims off a trailing / from whatever the input string is.
The second substitution assigns the value / if the input is null, i.e. it used to be just / before it was trimmed to nothing. The first code suggestion just merges these two together.

I hope that this helps,
Robin

Another approach:-

awk '/[^/]+/{sub(/\/$/,X)}1'

You are spawning another process with that though and not very easy to understand if you are not a awk Jedi Master like yourself.

@rbatte1: in my bash , my_dir="${my_dir%/:=/}" doesn't work. Is that a "bashism" or do I do sth. wrong?

thanks

awk '/[^/]+/{sub(/\/$/,X)}1' 

works

can you explain the same

Hi Yoda, the / character needs to be escaped within an awk regex constant expression that is terminated by two slashes, even within a bracket expression:

awk '/[^\/]/{sub("/$",x)}1'

awk: Regular Expressions

---
Other options:

sed 's|\(.\)/$|\1|'
perl -pe 's/(?<=.)\/$//'

/[^/]+/ - if record has one or more occurrence of any character other than / (to exclude root fs)

sub(/\/$/,X) - substitute or replace / in the end with X which is null or undefined variable.

1 - a non zero value or true, forces awk to print record.