替换管道字符“|”与转义的点子字符“\ |”在bash脚本中的字符串

时间:2016-08-03 13:46:59

标签: bash tr

我正在尝试用String中的转义字符替换String中的管道字符:

输入:“text | jdbc” 输出:“text \ | jdbc”

我用tr尝试了不同的东西:

echo "text|jdbc" | tr "|" "\\|"
...

但他们都没有奏效。 任何帮助,将不胜感激。 谢谢,

3 个答案:

答案 0 :(得分:11)

tr适用于一对一的字符映射(读“翻译”)。 \|是两个字符,您不能使用tr。您可以使用sed

echo 'text|jdbc' | sed -e 's/|/\\|/'

此示例替换了一个|。如果要替换多个,请添加g标志:

echo 'text|jdbc' | sed -e 's/|/\\|/g'

@JuanTomas的一个有趣提示是使用不同的分隔符来提高可读性,例如:

echo 'text|jdbc' | sed -e 's_|_\\|_g'

答案 1 :(得分:2)

您可以利用|bash中的特殊字符这一事实,这意味着%q使用的printf修饰符将为您转义:< / p>

$ printf '%q\n' "text|jdbc"
text\|jdbc

不需要|特别处理的更通用的解决方案是

$ f="text|jdbc"
$ echo "${f//|/\\|}"
text\|jdbc

${f//foo/bar}展开f并将foo的每次出现替换为bar。这里的运营商是/;当后面跟着另一个/时,它会替换所有出现的搜索模式而不是第一个搜索模式。例如:

$ f="text|jdbc|two"
$ echo "${f/|/\\|}"
text\|jdbc|two
$ echo "${f//|/\\|}"
text\|jdbc\|two

答案 2 :(得分:0)

您可以尝试echo "text|jdbc" | awk -F'|' '$1=$1' OFS="\\\|"

public class ServiceFactory<TService> where TService : WebServicesClientProtocol, new()
{

    public static TService GetSecureService(string serviceUrl, X509Certificate certificate)
    {
        if (serviceUrl == null)
        {
            throw new ArgumentNullException(nameof(serviceUrl), "Service URL must be specified.");
        }

        if (serviceUrl == string.Empty)
        {
            throw new ArgumentException("Service URL cannot be empty.", nameof(serviceUrl));
        }

        if (certificate == null)
        {
            throw new ArgumentNullException(nameof(certificate), "Client certificate must be specified.");
        }

        return Service(serviceUrl, certificate);
    }

    private static TService Service(string serviceUrl, X509Certificate certificate)
    {
        return ConfigureService((TService)Activator.CreateInstance(typeof(TService)), serviceUrl, certificate);
    }

    public static TService ConfigureService(TService service, string serviceUrl, X509Certificate certificate)
    {
        service.PreAuthenticate = true;
        service.Credentials = CredentialCache.DefaultCredentials;
        service.Timeout = 250;
        service.Url = serviceUrl;

        return ConfigureRequestSignature(service, certificate);
    }

    private static TService ConfigureRequestSignature(TService service, X509Certificate certificate)
    {
        X509SecurityToken signatureToken = new X509SecurityToken(certificate);
        MessageSignature signature = new MessageSignature(signatureToken);

        signature.SignatureOptions = SignatureOptions.IncludeTimestamp | SignatureOptions.IncludeSoapBody | SignatureOptions.IncludeMessageId | SignatureOptions.IncludeAction;

        SoapContext requestContext = service.RequestSoapContext;
        requestContext.Security.Tokens.Add(signatureToken);
        requestContext.Security.Elements.Add(signature);

        // TTL must be less than 60 seconds, otherwise the request will be discarded.
        requestContext.Security.Timestamp.TtlInSeconds = 50;

        return service;
    }
}