Replace a String in a File with Contents Copied from Another File

Replace a string in a file with contents copied from another file

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

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

EDIT:

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

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

Replace a string in one file with another string in another file

You can read the first file into a dictionary, and then use re.sub:

import re
d = dict(re.split('\s+', i.strip('\n')) for i in open('filename.txt'))
content = [i.strip('\n') for i in open('filename2.txt')]
with open('results.txt', 'w') as f:
f.write('\n'.join(re.sub('(?<=\<\!\-\-\s)\d+(?=\s\-\-\>)', lambda x:d[x.group()], i) for i in content))

Output:

...text... <!-- name44 --> ...text...
...text... <!-- name2 --> ...text...
...text... <!-- name3 --> ...text...
...text... <!-- name94 --> ...text...

replace string in a file with value from another file

awk 'NR==FNR{a[$2]=$1;next}{$1=a[$1];}1' fileA fileB

NR==FNR{a[$2]=$1;next} => This is true when the fileA is processed. An associative array is formed where the index is the 2nd column with the 1st column as its value.

{$1=a[$1];} => When the second file is processed, Replace the 1st column with the appropriate value stored in the array.

1 => Print every line.

Copy and replace content in string of file name

There is no need for sed, use Parameter Expansions:

$ file=boot-1.5-SNAPSHOT.jar
$ echo ${file/-SNAPSHOT/}
boot-1.5.jar

or

$ cp "$file" "${file/-SNAPSHOT/}"

In this case:

${parameter/pattern/string}

Pattern substitution. The pattern is expanded to produce a
pattern just as in pathname expansion. Parameter is expanded and
the longest match of pattern against its value is replaced with string.

Note that since you are dealing with files, you should quote the variables (otherwise files with whitespace characters will mess things up).

Furthermore it is possible, that you should create a symbolic link instead of a copy:

$ ln -s "$file" "${file/-SNAPSHOT/}"

File get contents and string replace for multiple files

Just foreach what you want:

foreach (['alpha.php', 'beta.php', 'gamma.php'] as $filename) {
$file = file_get_contents("./test/$filename");

if(strpos($file, "Hello You") !== false){
echo "Already Replaced";
}
else {
$str = str_replace("Go Away", "Hello You", $file);
file_put_contents("./test/$filename", $str);
echo "done";
}
}

You don't need the if unless you really need the echos to see when there are replacements:

foreach (['alpha.php', 'beta.php', 'gamma.php'] as $filename) {
$file = file_get_contents("./test/$filename");
$str = str_replace("Go Away", "Hello You", $file);
file_put_contents("./test/$filename", $str);
}

Or you can get the count of replacements:

    $str = str_replace("Go Away", "Hello You", $file, $count);
if($count) {
file_put_contents("./test/$filename", $str);
}

On Linux you could also try exec or something with replace or repl as they accept multiple files.

How to search and replace text in a file?

fileinput already supports inplace editing. It redirects stdout to the file in this case:

#!/usr/bin/env python3
import fileinput

with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
for line in file:
print(line.replace(text_to_search, replacement_text), end='')

How to replace specific String in a text file by java?

In general you can do it in 3 steps:

  1. Read file and store it in String
  2. Change the String as you need (your "username,password..." modification)
  3. Write the String to a file

You can search for instruction of every step at Stackoverflow.

Here is a possible solution working directly on the Stream:

public static void main(String[] args) throws IOException {

String inputFile = "C:\\Users\\geheim\\Desktop\\lines.txt";
String outputFile = "C:\\Users\\geheim\\Desktop\\lines_new.txt";

try (Stream<String> stream = Files.lines(Paths.get(inputFile));
FileOutputStream fop = new FileOutputStream(new File(outputFile))) {
stream.map(line -> line += " manipulate line as required\n").forEach(line -> {
try {
fop.write(line.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
});
}
}


Related Topics



Leave a reply



Submit