-2

I have some paths like so:

/dir
/dir//
/dir///
/path/to/dir
/path/to/dir/
/path/to/dir///
/path/to/dir/////////

I want to make it clearer using bash. I want to remove all / characters at the end of path and having: /path/to/dir or /dir without / at the end.

yasin
  • 99
  • 10
  • Welcome to SO. Stack Overflow is a question and answer site for professional and enthusiast programmers. The goal is that you add some code of your own to your question to show at least the research effort you made to solve this yourself. – Cyrus Aug 04 '18 at 06:40
  • @Cyrus What I did is removing only one last `/` using `sed` command. So I need help in order to remove all `/` at the end of string... So it could be quite difficult – yasin Aug 04 '18 at 06:43
  • @yasin, it is always good to add your efforts in your post as we all are here to learn, also try to mention all details in a single shot in your post. cheers and happy learning. – RavinderSingh13 Aug 04 '18 at 06:51
  • 1
    `sed 's|/*$||' file` – Cyrus Aug 04 '18 at 07:01
  • 1
    if you need to remove it from a bash variables, see also https://stackoverflow.com/a/27846529 (requires extglob) – Sundeep Aug 04 '18 at 07:07
  • 1
    See: [The Stack Overflow Regular Expressions FAQ](http://stackoverflow.com/a/22944075/3776858) – Cyrus Aug 04 '18 at 07:21

2 Answers2

1

This might be a possible solution:

sed -e 's/[/]*$//g'

For instance:

echo '/path/to/dir/////////' | sed -e 's/[/]*$//g'

gives you:

/path/to/dir
Lino
  • 3,968
  • 3
  • 14
  • 32
  • 2
    @Lino, please use single quotes unless double is needed.. won't make a difference here, but it is a good practice to follow.. see https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash and https://stackoverflow.com/questions/7680504/sed-substitution-with-bash-variables for details – Sundeep Aug 04 '18 at 06:58
  • Beware, `*` means zero or more, so this will always match in the regexp above. Perhaps `s/\/\+$//g` or `s#//*$##g` would be better. – potong Aug 04 '18 at 07:43
  • @potong Could you show me exception of Lino's solution? – yasin Aug 04 '18 at 09:25
  • @yasin Lino's solution is correct but always substitutes even when there is nothing to substitute. This may lead to the wrong mindset especially at a later date when if the RHS of the substitution command is amended e.g. `<< – potong Aug 04 '18 at 09:49
  • Using / as the delimiter means you have to escape it in the regexp. just don't do that. `s:/*$::`. – Ed Morton Aug 04 '18 at 14:40
1

Following awk may help you here.

awk '{sub(/\/+$/,"")} 1'  Input_file
RavinderSingh13
  • 101,958
  • 9
  • 41
  • 77