3

For each line in my file, if the line ends with / I want to remove it. How to do this? My attempt:

sed -e "s/$\/$//" myfile.txt > myfile_noslash.txt

Did not work.

5

Your command simply has an errant dollar sign. Fixed:

sed -e 's/\/$//' myfile.txt > myfile_noslash.txt
  • 3
    Use another delimiter, then there is no need for backslash: sed 's%/$%%' – rexkogitans Mar 2 at 16:01
  • 1
    @rexkogitans True. But as OP also used the escaped slash, it makes it clearer where his mistake is. That's why I also used -e. – Freddy Mar 2 at 16:12
  • 2
    I believe that many people do not even know that the delimiter can be chosen freely, hence I mentioned it. – rexkogitans Mar 2 at 20:13
9

Your command would try to delete a $ followed by a / at the end of the lines in your file.

You don't need the initial $ in the regular expression:

sed 's/\/$//' myfile.txt >myfile_noslash.txt

The substitution command s in sed can take almost any character as its delimiting character, for example

s@/$@@

or

s,/$,,

or

s|/$||

So your command could be

sed 's,/$,,' myfile.txt >myfile_noslash.txt
  • I find the underscores harder to read when they coalesce together: perhaps a hyphen or tilde would make a better delimiter? Hyphen has the advantage of not needing the shift key. – D. Ben Knoble Mar 2 at 15:20
  • 1
    @D.BenKnoble True. I'm changing that one to commas instead. – Kusalananda Mar 2 at 15:32
  • 2
    @D.Ben Personally I like the pipe cause it's so easy to look at and see the different sections in the expression – wjandrea Mar 3 at 1:04
1

You can use any character as a delimiter in the regex

sed -e 's%/$%%' myfile.txt > myfile_noslash.txt

1

Tried with below python and worked fine

#!/usr/bin/python
import re
k=open('l.txt','r')
for i in k:
    print re.sub("/$","",i).strip()
  • 2
    It's recommended to use with open('l.txt') as k: (which can also accept mode string). The with open() is a context manager, which will close the file properly without having to explicitly do so. stackoverflow.com/a/31334226/3701431 Otherwise, OK answer. Regex is not particularly necessary though - built in methods could handle it – Sergiy Kolodyazhnyy Mar 2 at 22:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.