Guy
Guy

Reputation: 14820

How do I use tr to substitute '--' string

I have an output:

--
out1
--
out2
--
out3

I want to get the output:

out1
out2
out3

I thought of using:

tr '--' ''

but it doesn't recognize '--' to be the first string I want to substitute. How do I solve this?

Upvotes: 4

Views: 8110

Answers (5)

Dennis Williamson
Dennis Williamson

Reputation: 360395

The best you can do with tr is delete the hyphens leaving blank lines. The best way to do what you want is Amro's answer using sed. It's important to remember that tr deals with lists of characters rather than multi-character strings so there's no point in putting two hyphens in your parameters.

$ tr -d "-" < textfile
out1

out2

out3

However, in order to have tr handle hyphens and additional characters, you have to terminate the options using -- or put the hyphen after the last character. Let's say you want to get rid of hyphens and letter-o:

$ tr -d "-o" < textfile
tr: invalid option -- 'o'
Try ‘tr --help’ for more information.

$ tr -d -- "-o" < textfile
ut1

ut2

ut3

$ tr -d "o-" < textfile
ut1

ut2

ut3

It's often a good idea to use the -- option terminator when the character list is in a variable so bad data doesn't create errors unnecessarily. This is true for commands other than tr as well.

tr -d -- "$charlist" < "$file"

Upvotes: 3

VNS
VNS

Reputation: 158

You can do the same thing with grep as well:

cat filename |grep -v "\--"

Upvotes: -1

ghostdog74
ghostdog74

Reputation: 342739

another way with awk

awk '!/^--$/' file

Upvotes: 3

Jerry Coffin
Jerry Coffin

Reputation: 490408

Why not use grep -v "^--$" yourfile.txt ?

Upvotes: 7

Amro
Amro

Reputation: 124563

cat file | sed '/^--/d'

Upvotes: 8

Related Questions