我想从路径 /test/path/ 替换 / 到 /replace
即预期输出应该是 =test=path=to=replace
答案1
#! /usr/bin/env bash
A="/test/path/to/replace"
B="${A////=}"
echo "$B"
结果:
=test=path=to=replace
答案2
这里有几个选项。您可以使用tr
new_path=$(echo '/test/path/to/replace' | tr '/' '=')
或者sed
new_path=$(echo '/test/path/to/replace' | sed 's/\//=/g')
答案3
这里可以使用sed命令。
sed "s/\//=/g"
命令输出示例:
pwd | sed "s/\//=/g"
echo "/test/path/to/replace" | sed "s/\//=/g"
文件示例(将文件内文本中的“/”更改为“=”):
sed "s/\//=/g" file_name
变量示例(更改变量内容;“/”改为“=”):
echo $var1 | sed "s/\//=/g"
当然,您可以替换“默认”分隔符(斜杠“/”),例如减号“-”;在这种情况下,您可以避免使用反斜杠符号并获得更好的可读性:
sed "s-/-=-g"
说明(如果你们中的一些人不太熟悉 sed 命令):
sed "s/\//=/g"
sed - stream editor (non-interactive command-line text editor)
s - substitute sed command
/ - separators - first, third and fourth slash sign
\ - used for escaping second slash sign so that bash interprets second slash sign as litteral slash sign - not as separator)
/ - second slash sign; litteral slash sign (not separator) - term that we want to replace
= - term that we want to get after replacement
g - global sed command (replace all slashes, not just first one - without 'g' sed will replace only first slash in the path)
sed "-/-=-g"
All the same as in the previous explanation, except the two things:
1. We don't use escape sign (backslash) and
2. minus signs represent separators.