Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

unix

sed

awk

tr

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?

Mac OS X Yosemite, bash 3.2.57(1)-release

like image 658
leetbacoon Avatar asked Dec 14 '22 17:12

leetbacoon


2 Answers

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.

like image 164
chepner Avatar answered Feb 05 '23 15:02

chepner


awk to help here.

awk '{sub(/: OK$/,"")} 1'  Input_file
like image 34
RavinderSingh13 Avatar answered Feb 05 '23 17:02

RavinderSingh13