Replace all instances of a string in a file

How to Replace all instances of a string in a file?

You can translate the content of this page by selecting a language in the select box.

How to Replace all instances of a string in a file?

  1. Open the file in read mode using the open() function.
  2. Read the contents of the file into a string using the read() method.
  3. Use the replace() method to replace all instances of the target string with the new string.
  4. Open the file in write mode using the open() function.
  5. Write the modified string to the file using the write() method.
  6. Close the file using the close() method.

Here is an example code snippet:

How to Replace all instances of a string in a file?
How to Replace all instances of a string in a file?

This will replace all instances of old_string with new_string in the file file.txt.

# Open the file in read mode
with open(‘file.txt’, ‘r’) as f:
# Read the contents of the file into a string
contents = f.read()

# Replace all instances of the target string
contents = contents.replace(‘old_string’, ‘new_string’)

# Open the file in write mode
with open(‘file.txt’, ‘w’) as f:
# Write the modified string to the file
f.write(contents)

# Close the file
f.close()


AI Unraveled: Demystifying Frequently Asked Questions on Artificial Intelligence

Shell script to replace all instances of a string in a file on Linux & Windows.

  • On Linux via bash script

    sed “s/$stringToReplace/$replaceWith/g” $File_Name > $File_Name

  • On Windows using Powershell

    ( get-content $File_Name ) | % { $_ -replace $stringToReplace, $replaceWith } | set-content $File_Name

  • On Windows using Batch

    set str=teh cat in teh hat
    echo.%str%
    set str=%str:teh=the%
    echo.%str%

    Script Output:
    teh cat in teh hat
    the cat in the hat

  • On Windows or Linux using Perl

    perl -pi.orig -e “s///g;”

  • On Windows or Linux using Python

Source:

  1. http://stackoverflow.com/questions/60034/how-can-you-find-and-replace-text-in-a-file-using-the-windows-command-line-envir

Search all files containing a specific string

You can translate the content of this page by selecting a language in the select box.

How to search all files containing a specific string on Linux and Windows?

  • On Linux

    grep -rnw ‘directory’ -e “pattern”
    grep –include=\*.{txt,log} -rnw ‘directory’ -e “pattern”
    This will only search for files with .txt or .log extension.
    grep –exclude=*.txt -rnw ‘directory’ -e “pattern”
    This will exclude files with .txt extensions.

  • On Windows

    CD Location
    FINDSTR /L /S /I /N /C:”pattern” *.log

Browse the internet via command line

You can translate the content of this page by selecting a language in the select box.

How to browse the internet via command line on Linux and Windows?

  • On Linux

    lynx http://google.ca
    If you don’t have lynx on your linux installation, you will have to install it. On Linux Red hat, install it like this:
    yum list lynx (to check the availability of the package)
    yum -y install lynx (to install the package)
    you can also use: curl -0 http://yoursite/index.html to get the source code of a specific file.

  • On Windows

    start /max http://google.ca
    Will open the url using your default browser.

Check how many CPU cores on Windows and on Linux

You can translate the content of this page by selecting a language in the select box.

How to check how many CPU cores I have on Windows & Linux?

What is a core in a CPU?
In summary, a core is a small CPU or processor built into a big CPU or CPU socket. It can independently perform or process all computational tasks. From this perspective, we can consider a core to be a smaller CPU or a smaller processor within a big processor.
Today, CPUs have been two and 18 cores, each of which can work on a different task. A core can work on one task, while another core works a different task, so the more cores a CPU has, the more efficient it is.

Open a command prompt (Windows) or Terminal (Linux) and type:

  • Windows: WMIC CPU Get /Format:List
    Capture_Check_CPU_Cores
  • Linux: cat /proc/cpuinfo | grep processor | wc -l
    For more details on Linux: ls /sys/devices/system/cpu/

What does 4 CPU cores mean?
A quad-core CPU has four processing cores in a single chip. It is similar to a dual-core CPU, but has four separate processors (rather than two), which can process instructions at the same time.

Linux & App Servers Monitoring Tricks

You can translate the content of this page by selecting a language in the select box.

LINUX & APPLICATION SERVERS MONITORING TRICKS


Objective:

  • Prevent server from going down,
  • detect what caused the server to go down,
  • get servers back after failure.
  • Explain what caused the server to fail

I – Regularly watch your monitoring  tool(s) (Nagios, Wily,top, …..)

On some of those tools,  you can see a graph of the apps CPU Load Average, CPU Used Percentage, Disk Usage percentage, memory used percentage, Network Bandwidth, Swap Used percentage.

II – Check ulimit count (Number of files opened by applications like tomcat, oracle,…)

[Server]# ulimit -n
1024
If the number of files opened is getting closer to ulimit count (1024), increase the ulimit and talk to dev to identify and fix the process that is causing that.
To increase ulimit count for a specific application account, run the command  ulimit –n [value]
Ulimit can be set to whatever you want. Its one of those things that’s put in place as a throttle to keep things from going too nuts. Some systems will actually just set it to unlimited.


AI Unraveled: Demystifying Frequently Asked Questions on Artificial Intelligence

III- Port Monitoring 
Check number of connections to ports used by your apps

IV- Thread dump (stack trace of all threads ) If you have a high cpu percentage

[Server]# kill -3 (The output is printed in catalina.out) to see what is causing this and send it to developers.

V- Disk space /[drive_name] filling up quickly
Identify the file(s) that are filling up the disks. Most of the time ,it will be logs files.
[Server]# du -ks /[drive_name]/* | sort -nr | head
5719076 /[drive_name]/catalina
3675672 /[drive_name]/data
3287436 /[drive_name]/source
2044316 /[drive_name]/servers
319404 /[drive_name]/images
16 /[drive_name]/lost+found
By running this command on the larger folder, that will lead you to the files that eat the disk space.
Back up, remove or empty the file in question given that it won’t break the system.
If the log files are responsible for the disk filling up, let the developer know about it so that they can solve it. In the meantime, empty the log file with the command:

[Log_File_Location]# echo -n > Large_Log_File_Name.log

VI- Watch catalina.out and log4j.out after staging and live deploy, especially when you are restarting the servers.

If you are looking for an all-in-one solution to help you prepare for the AWS Cloud Practitioner Certification Exam, look no further than this AWS Cloud Practitioner CCP CLFC01 book below.


Achieve AWS Solutions Architect Associate Certification with Confidence: Master SAA Exam with the Latest Practice Tests and Quizzes illustrated

 

[Server]# tail -f log4j.log
VII- Start app servers properly
Before restarting app servers, make sure there is no app pid running for that specific server.

"Become a Canada Expert: Ace the Citizenship Test and Impress Everyone with Your Knowledge of Canadian History, Geography, Government, Culture, People, Languages, Travel, Wildlife, Hockey, Tourism, Sceneries, Arts, and Data Visualization. Get the Top 1000 Canada Quiz Now!"


[Server_Name]$ ps -ef | grep oracle
Kill the pid for that server.

IX – Cpu Load level

I would say that if we peak under 70% CPU during high traffic, we are doing well and have room. A good level to be ticking over at would be 30% used.
[Server]# top
top – 12:37:29 up 47 days, 23:09, 4 users, load average: 0.20, 0.20, 0.22
Tasks: 189 total, 1 running, 178 sleeping, 10 stopped, 0 zombie
Cpu(s): 1.2%us, 0.1%sy, 0.0%ni, 97.5%id, 1.0%wa, 0.0%hi, 0.1%si, 0.0%st

X- Server specific status pings (To assure the server are up and serving contents)
Write scripts for this

XI- Garbage collection stats

Invest in your future today by enrolling in this Azure Fundamentals - Pass the Azure Fundamentals Exam with Ease: Master the AZ-900 Certification with the Comprehensive Exam Preparation Guide!

Microsoft Azure AZ900 Certification and Training

If you are interested in any garbage collection stats there’s the gc.log files on each of the appservers (bad thing about it is it doesn’t do any date stamping so you can see how memory fluctuates but its a difficult to create a chart over time). In the past I’ve thought it might be good idea to write a cron that archived it daily so that you could at least break things down day by day.

XII- DB Connection

XIII- Load Average Monitoring script
Set up a  cron that just email sysadmin when the load average is above 3.

XIV – Find out who is monopolizing or eating the CPUs
[Server]# ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10

Djamgatech: Build the skills that’ll drive your career into six figures: Get Djamgatech.


error: Content is protected !!