如何使用tr将一个字符替换为两个字符 [英] How to replace one character with two characters using tr

查看:47
本文介绍了如何使用tr将一个字符替换为两个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

tr 可以用两个字符替换一个字符吗?

Can tr replace one character with two characters?

我试图用~\n"替换~",但输出没有产生换行符.

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

$ echo "asdlksad ~ adlkajsd ~ 12345" | tr "~" "~\n"
asdlksad ~ adlkajsd ~ 12345

推荐答案

不,tr 专门用于用单个字符替换单个字符(或者,根据命令行选项,删除字符或将单个字符的运行替换为一次.

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 可能是这项特定工作的最佳工具:

sed is probably the best tool for this particular job:

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

(请注意,这需要 sed 将 backlash-n \n 序列解释为换行符.GNU sed 会这样做,但是 POSIX 除了在正则表达式中没有指定它,而且肯定有旧版本的 sed 没有.)

(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.)

这篇关于如何使用tr将一个字符替换为两个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆