Unix & Linux Asked by watery on October 31, 2021
I’m using the tr
command to replace newlines with tabs from an output of another command, and I want to have multiple tabs to better align the output to a columnar format.
I see that tr
has a [CHAR*REPEAT]
option, where REPEAT
could be a decimal or octal value, but I can’t get it to work, e.g. the following simple line:
echo "1234" | tr ['2'] ['x'*3]
gives:
1x34
while I’m expecting:
1xxx34
What’s the correct syntax to use?
I'm afraid you are misunderstanding the meaning of the "repeat" option.
tr
, as you correctly infer, is used to translate character sets. You call it with option
tr set1 set2
The idea is that both sets can contain multiple characters, i.e. you can say
tr 'abc' 'def'
and it will replace every a
with a d
, every b
with an e
, and every c
with an f
. Now, sometimes you want to replace multiple "input" characters with the same "output" character, say
tr 'abcdefghij' 'xxxxxxxxyz'
This will replace a
to h
with x
, i
with y
, and j
with z
. The "repeat" function is meant to make writing this less cumbersome, so that you can instead write
tr 'abcdefghij' '[x*8]yz'
as shorthand. Unfortunately, that means it is not designed for what you intend to do.
Instead, you can try sed
$ echo "1234" | sed 's/2/xxx/g'
1xxx34
This will substitute (s
) all occurences (the trailing g
) of 2
with xxx
. Since sed
is far more powerful than that (have a look at the questions tagged as sed for an overview of what is possible), it may be a good idea to have a look into anyway.
Answered by AdminBee on October 31, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP