Shell – Remove forward-slash using sed

sedshell

I have a text file that contains following

https://git.centos.org/git/rpms/abc.git
https://git.centos.org/git/rpms/abc.git/
https://git.centos.org/git/rpms/abc

When I run the following command,

reponame=$(echo $url | awk -F/ '{print $NF}' | sed -e 's/.git\/$//' | sed -e 's/.git//')
echo $reponame

I am supposed to get

abc

It fails for the lines ending in .git/ but it works for the other 2 cases.

Best Answer

You have to remove the trailing slash before you print the last field with awk. Otherwise the last field will be empty.

Use

echo "$url" | sed -e 's#/$##' -e 's/\.git$//' | awk -F / '{print $NF}'

or even

echo "$url" | sed -e 's#/$##' -e 's/\.git$//' -e 's#^.*/##'

Tips:

  • You can give several sed commands to one invocation of sed so it is sometimes not necessary to pipe from sed to sed. Either sed -e 'cmd1' -e 'cmd2' ... or sed 'cmd1;cmd2;...' will work.
  • You can use a different delimiter for the s command of sed so you do not have to escape slashes in the pattern (I used # as a delimiter).
Related Question