Find and replace text within a file using commands

sed -i 's/original/new/g' file.txt


sed = Stream EDitor -i = in-place (i.e. save back to the original file)

The command string:

s = the substitute command original = a regular expression describing the word to replace (or just the word itself) new = the text to replace it with g = global (i.e. replace all and not just the first occurrence)

file.txt = the file name

There are a number of different ways to do this. One is using sed and Regex. SED is a Stream Editor for filtering and transforming text. One example is as follows:

marco@imacs-suck: ~$ echo "The slow brown unicorn jumped over the hyper sleeping dog" > orly marco@imacs-suck: ~$ sed s/slow/quick/ < orly > yarly marco@imacs-suck: ~$ cat yarly The quick brown unicorn jumped over the hyper sleeping dog

Another way which may make more sense than < strin and > strout is with pipes!

marco@imacs-suck: ~$ cat yarly | sed s/unicorn/fox/ | sed s/hyper/lazy/ > nowai...
0 0
To replace all instances of a string in a directory (subdirectories included) do:


perl -e "s/FIND/REPLACE/g;" $(find path/to/DIRECTORY -type f) The above will make a backup temp file of your original
If you do not want a temp file with the .save extension then do:


perl -e "s/FIND/REPLACE/g;" -pi $(find path/to/DIRECTORY -type f) --------------------
You want to replace all instances of the word "design" with "dezine" in the directory /public_html/company/info

you can execute the command from document root as


perl -e "s/design/dezine/g;" $(find public_html/company/info -type f) or you can execute the command from public_html/company/ (a directory above) as:


perl -e "s/design/dezine/g;" $(find info -type f) ------------------------------

The above commands will search all files (.gif, .jpg, .htm, .html, .txt) so you might see some error messages "Can't...

0 0

Hey, Scripting Guy! From the command line, how can I use a script to open a file and replace text; for example, how can I replace all instances of “Jim” with “James”?

— JW

Hey, JW. As we’ve found out numerous times when dealing with text files, there is no obvious way to do this; that is, there is no ReplaceText command that can open a text file and find and replace text. Fortunately, this problem is typical of text file questions in one other respect: although there’s no obvious way to carry out the task, we can still find a way to get the job done.

Although we can’t directly search and replace text inside a text file, we can do the next best thing. We can: 1) open up a text file; 2) read the text into a variable; 3) do a search-and-replace on that variable; and 4) re-save the text file. We can even do all that from the command line, although we’ll hold off on that for a moment. Instead, let’s start with a simple script that carries out the...

0 0
Read all about it here

IMPORTANT: If you use quotes or backslashes in command line find/replace text, please regenerate your commands before using fnr.exe in batch file. The logic for encoding quotes and slashes has changed in 1.7 to cover all common cases where users had issues.

Version 1.6 has been released on Mar 24th, 2014
Read all about it here

Version 1.5 has been released on Nov 6th, 2013
Read all about it here

An open source tool to find and replace text in multiple files.

Single file download - fnr.exe (181kb) Replace text in multiple files using windows application or through command line Find Only to see where matches are found Case-sensitive searching Searching for files in one directory or recursing sub-directories Regular expressions Find and replace multi-line text Generate command line button to create command line text to put in batch file Command line help Unit tests of Find/Replace engine

For screenshots I used a...

0 0

The Find and Replace control appears in the upper right corner of the code editor window. The Find and Replace control immediately highlights every occurrence of the given search string in the current document. You can navigate from one occurrence to another by choosing the Find Next button or the Find Previous button on the search control.

You can access replacement options by choosing the button next to the Find text box. To make one replacement at a time, choose the Replace Next button next to the Replace text box. To replace all matches, choose the Replace All button.

To change the highlight color for matches, choose the Tools menu, select Options, and then choose Environment, and select Fonts and Colors. In the Show settings for list, select Text Editor, and then in the Display items list, select Find Highlight...

0 0
Command Line help: Find and Replace text within multiple files?

location: - date: August 28, 2010
I'm pretty sure this is doable from the command line, but my CLI skills have degraded a lot since my pre-Y2K admin days. The goal is to search all the files in the directory for a very long string of text and replace it with another string of text. The text being searched for is my Google Adsense code (which will be stripped from my website) and it will be replaced with a placeholder so I can easily tack something else in there in the future. Seeing how I have that long snip of code on about 100 pages, automating the process would make life easier. If I was searching for a single word, I can see ways to do this. If I paste the code I'm searching for into a text file, is there a way to: find (contents of oldstring.txt) and replace with (contents of newstring.txt)? Thanks, and sorry being less clear than possible, eb

Search And Replace Text Within...
0 0

Sometime we need to find and replace text in more than one files. The problem begins when we try to do so after opening each file. Certainly, you need only a couple of seconds to find and replace text in two or three files. However, just imagine that you have fifty files and you need to find and replace three words in each file. How do you handle that? Don’t panic. Here is a simple free tool for Windows and this is called Find and Replace Tool. This portable software can find and replace text in multiple files within moments.

Find and Replace Text in Multiple Files

First, download Find and Replace Tool and open it. As this is a portable software, you will not have to install it. After opening Find and Replace Tool, the following screen will be appeared,

The UI is uncluttered. Therefore, you will understand each and every option very quickly. However, just follow the following steps to find and replace text in multiple files using this free...

0 0
Jul 15, 2011

Is there a way to specify to find that I only want text files (and not binary files)? Grep has an option to exclude binary files, so I thought find probably has a similar feature, but I've been unable to find it.

Ubuntu :: Command Line - Find And Replace Text Within Multiple Files? General :: Find/grep/wc Command To Find Matching Files - Print Filename And Word Count? Programming :: Command For Find/Replace In Text Files (inc. Files In Sub-folders)? General :: Find Setuid Files Using FIND Command? OpenSUSE :: Find Files In 11.2 Without Using The Command Line Ubuntu :: Find Multiple Files In The Command Line? General :: Command To Find / Replace In A Text File? General :: Find Text Within Files? General :: SQL Like Group By And Sum For Text Files In Command Line? General :: Find And Replace Text From Many Files In A Dir? General :: Using Find Or Grep To Find A Group Of Text Strings? Ubuntu :: Find Command Does Not Find All Files? General :: Sed...
0 0

This article is part of on-going Unix Sed Tutorial series. In previous articles, we discussed about sed print operation and sed delete operation.

In this article let us review how to use sed substitute command “s”.

The `s’ command is probably the most important in `sed’ and has a lot of different options.

The `s’ command attempts to match the pattern space against the supplied REGEXP; if the match is successful, then that portion of the pattern space which was matched is replaced with REPLACEMENT.

Syntax: #sed 'ADDRESSs/REGEXP/REPLACEMENT/FLAGS' filename #sed 'PATTERNs/REGEXP/REPLACEMENT/FLAGS' filename s is substitute command / is a delimiter REGEXP is regular expression to match REPLACEMENT is a value to replace

FLAGS can be any of the following

g Replace all the instance of REGEXP with REPLACEMENT n Could be any number,replace nth instance of the REGEXP with REPLACEMENT. p If substitution was made, then prints the new pattern space. i match...
0 0

Finding and replacing text within a text file can be done using any text editor. Below is a listing of all the major text editors with information on how to replace text.

Tip: In most programs the Find and Replace option can be accessed by pressing the Ctrl + H or Ctrl + F keyboard shortcut on the PC. On Apple computers running macOS the shortcut key may be either Cmd + H or Cmd + F.

Replacing text within Notepad
Replacing text with WordPad
Replacing text in Microsoft Word
Replacing text with Notepad++
Replacing text in TextPad
Find and replace text in Excel

Using Search and Replace and advanced options
Use our online text tool to replace and modify any text

Replacing text within Notepad

Microsoft Notepad is included with all versions of Windows and can be used to replace text in plain text files. To replace text follow the steps below.

Open the text file by double-clicking on the file. In Notepad, click...
0 0

Use EmEditor’s integrated regular expression support with Unicode to make find and replace operations a breeze. The Find, Replace, Find in Files, and Replace in Files functions each allow you to make nuanced and agile changes to your work using regular expressions.

Regular Expressions find text patterns within an open document or in multiple files. A regular expression is a pattern of text that consists of ordinary characters, or literals, (for example, letters a-z) and special characters, known as metacharacters. The pattern describes one or more strings to match when searching text. EmEditor regular expression syntax is based on Perl regular expression syntax.

When using Regular Expressions, select the Find, Replace, Find in Files, or Replace in Files commands under the Search menu. Then check the Use Regular Expressions check box, and any other desired search parameters. Enter the Regular Expression to search for, and click Find. If using Replace or Replace in...

0 0

I have written a small hybrid JScript/batch utility called REPL.BAT that is very convenient for modifying files via the command line or a batch file. The purely native script does not require installation of any 3rd party executeable, and it works on any modern Windows version from XP onward. It is also very fast, especially when compared to pure batch solutions.

REPL.BAT simply reads stdin, performs a JScript regex search and replace, and writes the result to stdout.

Here is a trivial example of how to replace foo with bar in test.txt, assuming REPL.BAT is in your current folder, or better yet, somewhere within your PATH:

type test.txt|repl "foo" "bar" > move /y test.txt

The JScript regex capabilities make it very powerful, especially the ability of the replacement text to reference captured substrings from the search text.

I've included a number of options in the utility that make it quite powerful. For example, combining the M...

0 0

This uses a helper batch file called repl.bat - download from:

Place repl.bat in the same folder as the batch file or in a folder that is on the path.

Repl.bat is a hybrid batch file using native Windows scripting and is far faster than a regular batch script.

The L switch makes the text search and replace a literal string and I'd expect the 12 MB file to complete in several seconds on a modern PC.

@echo off &setlocal set "search=%~1" set "replace=%~2" set "textfile=Input.txt" set "newfile=Output.txt" call repl.bat "%search%" "%replace%" L < "%textfile%" >"%newfile%" del "%textfile%" rename "%newfile%"...
0 0

Found this thread among others and I agree it contains the most complete answers so I add mine too:

1) sed and ed are so hand!!! Look at this code from @Johnny:

sed -i -e 's/abc/XYZ/g' /tmp/file.txt

2) when my restriction is to use it by a shell script then, no variable can be used inside in place of abc or XYZ! This seems to agree with what I understand at least. So, I can't use:

x='abc' y='XYZ' sed -i -e 's/$x/$y/g' /tmp/file.txt #or, sed -i -e "s/$x/$y/g" /tmp/file.txt

but, what can we do? As, @Johnny said use a 'while read...' but, unfortunately that's not the end of the story. The following worked well with me:

#edit user's virtual domain result= #if nullglob is set then, unset it temporarily is_nullglob=$( shopt -s | egrep -i '*nullglob' ) if [[ is_nullglob ]]; then shopt -u nullglob fi while IFS= read -r line; do line="${line//''/$server}" line="${line//''/$alias}" line="${line//''/$user}" line="${line//''/$group}" ...
0 0

How do I find and replace (substitute) test using vi or vim text editor under UNIX / Linux / BSD or Apple OS X operating systems?

Both vi and vim text editor comes with substitute command for finding and replacing text.


The syntax is as follows:


The substitute command can be used as per your requirements.

Task: VI / Vim Basic Find and Replace

To find each occurrence of ‘UNIX’, and replace it with ‘Linux’, enter (press ESC, type : and following command):

Task: Find and Replace with Confirmation

Find a word called ‘UNIX’ and replace with ‘Linux’, but ask for confirmation first, enter:

Task: Find and Replace Whole Word Only

Find whole words exactly matching ‘UNIX’ to ‘Linux’; and ask for confirmation too:

Task: Case...

0 0

-exec COMMAND \;

Carries out COMMAND on each file that find matches. The command sequence terminates with (the ";" is escaped to make certain the shell passes it to find literally, without interpreting it as a special character).

If COMMAND contains , then find substitutes the full path name of the selected file for "{}".

Example 16-3. Badname, eliminate file names in current directory containing bad characters and whitespace.

Example 16-4. Deleting a file by its inode number

The find command also works without the -exec option.

See Example 16-30, Example 3-4, and Example 11-10 for scripts using find. Its manpage provides more detail on this complex and powerful command.

A filter for feeding arguments to a command, and also a tool for assembling the commands themselves. It breaks a data stream into small enough chunks for filters and commands to process. Consider it as a powerful...

0 0

Finding and replacing text in multiple text files at once isn’t new, but most people in businesses and homes use Word and Excel files, not text files. If you use Excel or Word extensively and would like to perform find and replace operations right from the desktop (and/or in batch), then check out ‘Replace Genius’, a program that recently became freeware.

‘Replace Genius’ allows you to find and replace text within Excel, Word, and text files. It can apply 10 different kinds of operations, many of which you’ve probably seen before and are familiar with from file renumbering programs, such as: inserting a string, trimming (removing leading or trailing spaces), renumbering, and adding counters, just to name a few.

But it can go a crucial step further, in that it allows you to combine your desired text manipulation operations together and save then in ‘presets’. Not only can you keep these for later use, but you can also use them to perform operations on files in...

0 0

It can be done in bash itself if you have control of the configuration file format. You just need to source (".") the configuration file rather than subshell it. That ensures the variables are created in the context of the current shell (and continue to exist) rather than the subshell (where the variable disappear when the subshell exits).

$ cat export parm_jdbc=jdbc:db2:// export parm_user=pax export parm_pwd=never_you_mind $ cat go.bash . echo "JDBC string is " $parm_jdbc echo "Username is " $parm_user echo "Password is " $parm_pwd $ bash go.bash JDBC string is jdbc:db2:// Username is pax Password is never_you_mind

If your config file cannot be a shell script, you can just 'compile' it before executing thus (the compilation depends on your input format).

$ cat parm_jdbc=jdbc:db2:// # JDBC URL parm_user=pax # user name ...
0 0