tr -d to remove an exact string of characters from a string
Asked Answered
C

2

7

I am trying to make tr -d remove a string of characters from an existing string, without it removing characters everywhere else.

For example, I want tr to remove : OK from the end of every string in foo.txt.

Contents of foo.txt:

BROKEN BONES: OK
Kefen Odvora: OK
BOOKS_FOR_MUM: OK
E: OK Amded: OK

This is the command I run:

cat foo.txt | tr -d ": OK$"

I want it to output this:

BROKEN BONES
Kefen Odvora
BOOKS_FOR_MUM
E: OK Amded

But instead I get this, which I don't want:

BRENBNES
efendvora
BS_FR_MUM
EAmded

How can I fix this?

Chronological answered 29/3, 2018 at 19:11 Comment(0)
S
18

You are using the wrong tool. You want sed, not tr:

cat foo.txt | sed 's/: OK$//'

or preferably

sed 's/: OK$//' foo.txt

when your input really is just a file, not a more complicated command.


tr -d removes all occurrences of any character found in the argument to -d; it does not treat it as a regular expression to match and remove. Specifically, you are removing all occurrences of :, , O, K, and $ from each line.

Situate answered 29/3, 2018 at 19:14 Comment(3)
IMHO sir, no need to use cat as sed could read Input_file itself.Connective
Yeah, I left that as a placeholder from the original question, in case the input was the output of a more complicated command. sed 's/: OK$//' foo.txt is sufficient if the input really is just a file.Situate
Works wonderfully, thank you! And yes, I will only be using this with plain text files. Now, if I were to use this with a complicated command, what would I need to use then?Chronological
C
1

awk to help here.

awk '{sub(/: OK$/,"")} 1'  Input_file
Connective answered 29/3, 2018 at 19:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.