用从另一个文件复制的内容替换文件中的字符串 [英] Replace a string in a file with contents copied from another file

查看:90
本文介绍了用从另一个文件复制的内容替换文件中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经弄清楚了,并尝试在gsed -i命令的帮助下替换字符串,如下所示:

I have figured out and tried replacing strings with the help of gsed -i command like this:

gsed -i 's/sdkUniqueKey=""/sdkUniqueKey="123"/g' AppConstants.txt

现在我想对文件中的另一个字符串执行相同的操作,但是正如我的问题所指出的那样,我需要先从另一个文件中复制内容,然后替换一个字符串,例如:

Now I want to do the same operation on another string in my file but as my question states, I need to copy the contents from a different file first and then replace a string, something like:

gsed -i 's/sdkPrivateKey=""/sdkPrivateKey="contentsCopiedFromAnotherFile"/g' AppConstants.txt

还有一件事,内容(要复制)具有下一行和空白,我想在复制之前将其删除.还带有反斜杠和正斜杠,希望他们在替换内容时不会造成任何问题).这是我要复制的内容:

One more thing, the contents (to be copied), have next line and white space in it, which I would like to remove before copying. Also it has backslash and forward slashes, hope they don't create any issues while replacing the content). Here is what I am trying to copy:

-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDNGillPEfz8d7W
0fyJejF9AYeo8OowcdOcxrpzs4IiXCwPEP1MOHAaOwGTdMwSAeQjw9WOYpE1q+DU
I+Zhh4DVUR8dIdYQtXe+oK/QfhVQMJ3AjTKRvhUmFciGwxXlnLBIkN/ePplNdq9Z
Y5DrSR0lE8X2dD+ZRAkQRpsY8TE48b9f443sbsU4sMvNaxd2XTxe2TLYRvB00w6Q
3lqZiKLzttINBCPoCjhJwBdhcF/LHsCmYhfElPqJxH27BTGBOnbICdmazdnChXQg
3hhsbJmnNDe17Spw0lY
-----END PRIVATE KEY-----

我也可以将文件的内容复制到变量中:

I am able to copy the contents of a file into a variable as well:

contents ="`cat fileToBeRead`"

我需要做的就是从此字符串中删除空格和换行,并在我的gsed命令中使用此"contents"变量

All I need is to remove white spaces and new lines from this string and use this "contents" variable in my gsed command

推荐答案

如果我已经正确理解了您的问题,则可以使用以下方法解决问题:

If I have properly understood your question, the following should do the trick:

#!/bin/bash

fileToBeRead="key.txt" #Whatever

var=$(tr -d '[:blank:]\n' < $fileToBeRead)
sed -i "s#sdkPrivateKey=\"\"#sdkUniqueKey=\"$var\"#g" AppConstants.txt

由于键中包含反斜杠/斜杠,因此您应该对sed使用不同的分隔符(例如#),否则句子将被错误地解析.

Since the key contains backslashes/slashes you should use a different separator for sed (e.g. #) or the sentence will be misparsed.

KEY="$var" perl -pi -e 's/sdkPrivateKey=""/sdkUniqueKey="$ENV{KEY}"/g' AppConstants.txt

为了避免sed的分隔符问题,可以使用

perl代替sed.在下面查看@DennisWilliamson的评论.

perl can be used instead of sed in order to avoid sed's separator issues. Check out @DennisWilliamson's comment below.

这篇关于用从另一个文件复制的内容替换文件中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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