Michael21 Asked: 2024-02-03 23:52:40 +0800 CST2024-02-03 23:52:40 +0800 CST 2024-02-03 23:52:40 +0800 CST 如何将字符串中的某个字符替换为某个字符串?[复制] 772 给定 bash 脚本中的一个字符串变量,其中包含一堆换行符 '\n',如何用字符串“abc\n”替换这些换行符?或者换句话说,如何在每个换行符前面插入“abc”? string 1 个回答 Voted Best Answer Dan C. Wlodarski 2024-02-04T00:08:59+08:002024-02-04T00:08:59+08:00 有很多方法可以使用 Bash 外部的命令/程序来“剥皮”。但是,如果您只想使用 Bash 内置函数: #!/usr/bin/env bash ## Store the newline character. readonly NEWLINE=$'\n' ## Fetch your content (hard-coded here for the example). original="one${NEWLINE}\ two${NEWLINE}\ three${NEWLINE}\ four${NEWLINE}\ five${NEWLINE}" ## Peform global substitution. substituted="${original//${NEWLINE}/ - abc${NEWLINE}}" ## Output result. echo -e "${substituted}" 基于https://linuxhandbook.com/replace-string-bash/
有很多方法可以使用 Bash 外部的命令/程序来“剥皮”。但是,如果您只想使用 Bash 内置函数:
基于https://linuxhandbook.com/replace-string-bash/