Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace one character with two characters using tr

Tags:

shell

unix

tr

Can tr replace one character with two characters?

I am trying to replace "~" with "~\n" but the output does not produce the newline.

$ echo "asdlksad ~ adlkajsd ~ 12345" | tr "~" "~\n" asdlksad ~ adlkajsd ~ 12345 
like image 448
Paolo Avatar asked Aug 21 '13 18:08

Paolo


People also ask

How do you replace characters with tr?

The `tr` command uses –s (–squeeze-repeats) option for search and replace any string from a text. In the following example, space (' ') is replaced by tab ('\t').

What is a tr character?

The tr command is a character translation filter, reading standard input (Section 43.1) and either deleting specific characters or substituting one character for another. The most common use of tr is to change each character in one string to the corresponding character in a second string.

Which option is used with tr command for deleting characters?

The -d ( --delete ) option tells tr to delete characters specified in SET1.


2 Answers

No, tr is specifically intended to replace single characters by single characters (or, depending on command-line options, to delete characters or replace runs of a single character by one occurrence.).

sed is probably the best tool for this particular job:

$ echo "asdlksad ~ adlkajsd ~ 12345" | sed 's/~/~\n/g' asdlksad ~  adlkajsd ~  12345 

(Note that this requires sed to interpret the backlash-n \n sequence as a newline character. GNU sed does this, but POSIX doesn't specify it except within a regular expression, and there are definitely older versions of sed that don't.)

like image 61
Keith Thompson Avatar answered Oct 04 '22 03:10

Keith Thompson


you could go with awk, let FS/OFS variable do the job for you:

awk -F'~' -v OFS="~\n" '$1=$1'  

test with your example:

kent$ awk -F'~' -v OFS="~\n" '$1=$1' <<< "asdlksad ~ adlkajsd ~ 12345"  asdlksad ~  adlkajsd ~  12345 
like image 31
Kent Avatar answered Oct 04 '22 01:10

Kent