How to Search File Text For a Pattern and Replace It With a Given Value

How to search file text for a pattern and replace it with a given value

Disclaimer: This approach is a naive illustration of Ruby's capabilities, and not a production-grade solution for replacing strings in files. It's prone to various failure scenarios, such as data loss in case of a crash, interrupt, or disk being full. This code is not fit for anything beyond a quick one-off script where all the data is backed up. For that reason, do NOT copy this code into your programs.

Here's a quick short way to do it.

file_names = ['foo.txt', 'bar.txt']

file_names.each do |file_name|
text = File.read(file_name)
new_contents = text.gsub(/search_regexp/, "replacement string")

# To merely print the contents of the file, use:
puts new_contents

# To write changes to the file, use:
File.open(file_name, "w") {|file| file.puts new_contents }
end

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='')

Several find and replace from text file

Using the regex supplied by jay.sf, you could use str_replace_all from the stringr package to do it with a named vector.

library(stringr)

new_tx <- str_replace_all(tx,
c("\\sis taken on\\s" = " ",
"\\b\\sat\\s" = "\t",
"\\b\\sp\\b" = ","))

cat(new_tx)

Result

-The data 1 Aug, 2009    UBC
and is significant with, value <0.01

-The data 2 Sep, 2012 SFU
and is not significant with, value > 0.06

How to replace a string in a text file which starts with a specific word and ends with a special character in C#?

In order to replace it with Regex you can use

var testText = "some other stuff Cleaning_e=12/43/4555, some more ";
var newValue = "78/65/0000";
var rx = new Regex(@"Cleaning_e=(\d\d/\d\d/\d\d\d\d)?");
var result = rx.Replace(testText, $"Cleaning_e={newValue}");

this will replace the date. Beware that this replaces every occurance of Cleaning_e and requires the date format to be exactly to have axactly 2 2 and 4 Digits. If the number of digits vary, you can use

var rx = new Regex(@"Cleaning_e=(\d+/\d+/\d+)?");

instead.

I'd rather recomment to parse this into a proper structure and change the values there rather than Manipulating the text file directly.

Find specific line from text file using two patterns then replace a variable string on that line

$ sed 's/\(expression "if((CONDITION1==1),\)[^,]*\(,CATEGORY1)"\)/\10.111111111\2/' file
expression "if((CONDITION1==1),0.111111111,CATEGORY1)"

Here's an example of why the part you don't capture should be [^,]* instead of .*:

$ cat file
expression "if((CONDITION1==1),0.999999999,CATEGORY1)" # this is ",CATEGORY1)"
expression "if((CONDITION1==1),0.999999999,FOO)" # this is not ",CATEGORY1)"

$ sed 's/\(expression "if((CONDITION1==1),\)[^,]*\(,CATEGORY1)"\)/\10.111111111\2/' file
expression "if((CONDITION1==1),0.111111111,CATEGORY1)" # this is ",CATEGORY1)"
expression "if((CONDITION1==1),0.999999999,FOO)" # this is not ",CATEGORY1)"

$ sed 's/\(expression "if((CONDITION1==1),\).*\(,CATEGORY1)"\)/\10.111111111\2/' file
expression "if((CONDITION1==1),0.111111111,CATEGORY1)"
expression "if((CONDITION1==1),0.111111111,CATEGORY1)"

Replacing a pattern in a text file with a random value

The best way I know how to do this is with a perl in-place edit:

E.g. myfile.txt contains:

\t (obj)
\t (obj)
\t (obj)

Run the in-place edit:

perl -i.bak -ne '$a=int(rand()*2000); s/\((.*?)\)/{$1$a}/g; print' myfile.txt

myfile.txt now contains:

\t (obj1869)
\t (obj665)
\t (obj1459)

Obviously adjust 2000 to your requirements.

EDIT: If you wish to use incrementing identifiers use:

perl -i.bak -ne '$a++; s/\((.*?)\)/{$1$a}/g; print' myfile.txt

How to replace a Request value after a specific pattern in text file?

Try this:

sed -e '/333/!{' -e 's#<AccountNumber>[0-9]*</AccountNumber>#<AccountNumber>333333333</AccountNumber>#;s#<BranchNumber>[0-9]*</BranchNumber>#<BranchNumber>33333</BranchNumber>#;}'

Eg:

$ sed -e '/333/!{' -e 's#<AccountNumber>[0-9]*</AccountNumber>#<AccountNumber>333333333</AccountNumber>#;s#<BranchNumber>[0-9]*</BranchNumber>#<BranchNumber>33333</BranchNumber>#;}'  test.txt
<Info>
<AccountNumber>333333333</AccountNumber>
<BranchNumber>33333</BranchNumber>
<TransitNumber>01646</TransitNumber>
<NameAndCity>XYZ Bank</NameAndCity>
<OwnerFullName>ABC XYZ</OwnerFullName>
</Info>

A very straightforward way, if you test ok and want to change the file inplace, add -i switch.

I don't have Solaris to test, so can't be sure.

Try this simple perl one see if it's working:

perl -pe 's#<AccountNumber>[0-9]*</AccountNumber>#<AccountNumber>333333333</AccountNumber>#' test.txt

If it's working, we can add others.

So for your logic first wrote in the question, it should be like this:

perl -pe 'unless (/333/) {s#<AccountNumber>[0-9]*</AccountNumber>#<AccountNumber>333333333</AccountNumber>#;s#<BranchNumber>[0-9]*</BranchNumber>#<BranchNumber>33333</BranchNumber>#;}' test.txt

You can add other substitudes yourself. the # is to replace the usual / of s, an easier way to avoid escape the / in close tags (I.E. s#from#to#;).

It's rather straightforward so I think you'll have no difficulty :)

Add -i switch to change inplace, like this: perl -i -pe '....



Related Topics



Leave a reply



Submit