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
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').
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.
The -d ( --delete ) option tells tr to delete characters specified in SET1.
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.)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With