3

I have a csv file with floats ending in a character:

1, 2, 6, 7, "p"
1, 6, 7, 2, "e"

etc.

I'd like to replace "p" with 0 and "e" with 1 for a classification task. That is, I would like:

1, 2, 6, 7, 0
1, 6, 7, 2, 1

For all 8000 lines in my file.

I have tried:

sed -i 's/"p"$/0' filename.csv

and

sed -i 's"p"$0//' filename.csv

but neither work. How can I replace several characters in each line using sed?

1
sed 's/"p"$/0/;s/"e"/1/' file.txt
  • 4
    Give a man a fish and you feed him for a day; teach a man to fish and you feed him for a lifetime. This is just a fish. – Oskar Skog Mar 6 '17 at 15:43
  • 6
    It's a delicious fish, though! – StatsSorceress Mar 6 '17 at 16:00
8
sed -e 's/"p"$/0/; t' -e 's/"e"$/1/' filename.csv

With t, we branch off if the first substitution succeeds, preventing the second substitution from being attempted. That's a common idiom for doing at most one substitution per line.

3

Your first sed is missing the terminating /. Use sed -i 's/"p"$/0/' filename.csv

  • You could add that the second uses " as a delimiter, and is also missing its terminating delimiter :) – Aaron Mar 6 '17 at 17:21
  • @Aaron The second sed in the question is just plain weird. Even if he added the " at the end, because the $ sign is after the quotes, it won't match the EOL, but rather replace p with a literal $0//. It was much easier to fix the first one. :) – Munir Mar 6 '17 at 18:06
  • Right, I missed that – Aaron Mar 6 '17 at 19:20

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.