- How to use sed to find and replace text in files in Linux / Unix shell
- Find and replace text within a file using sed command
- Syntax: sed find and replace text
- Examples that use sed to find and replace
- sed command problems
- How to use sed to match word and perform find and replace
- Recap and conclusion – Using sed to find and replace text in given files
- search and replace in files on linux (regex)
- 2 Answers 2
- Not the answer you’re looking for? Browse other questions tagged regex search replace or ask your own question.
- Related
- Hot Network Questions
- Subscribe to RSS
- Unix Sed Tutorial: Find and Replace Text Inside a File Using RegEx
- 1. Substitute Word “Linux” to “Linux-Unix” Using sed s//
- 2. Substitute all Appearances of a Word Using sed s//g
- 3. Substitute Only 2nd Occurrence of a Word Using sed s//2
- 4. Write Changes to a File and Print the Changes Using sed s//gpw
- 5. Substitute Only When the Line Matches with the Pattern Using sed
- 6. Delete Last X Number of Characters From Each Line Using sed
- 7. Eliminate Comments Using sed
- 8. Eliminate Comments and Empty Lines Using sed
- 9. Convert DOS newlines (CR/LF) to Unix format Using sed
- 10. Eliminate HTML Tags from file Using sed
- What GNU/Linux command-line tool would I use for performing a search and replace on a file?
- 4 Answers 4
- How can I replace a string in a file(s)?
- 9 Answers 9
- 1. Replacing all occurrences of one string with another in all files in the current directory:
- 2. Replace only if the file name matches another string / has a specific extension / is of a certain type etc:
- 3. Replace only if the string is found in a certain context
- 4. Multiple replace operations: replace with different strings
- 5. Multiple replace operations: replace multiple patterns with the same string
How to use sed to find and replace text in files in Linux / Unix shell
Find and replace text within a file using sed command
The procedure to change the text in files under Linux/Unix using sed:
- Use Stream EDitor (sed) as follows:
- sed -i ‘s/old-text/new-text/g’ input.txt
- The s is the substitute command of sed for find and replace
- It tells sed to find all occurrences of ‘old-text’ and replace with ‘new-text’ in a file named input.txt
- Verify that file has been updated:
- more input.txt
Let us see syntax and usage in details.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | sed utility on Linux, macOS or Unix-like OS |
Est. reading time | 4 minutes |
Syntax: sed find and replace text
The syntax is:
sed ‘s/word1/word2/g’ input.file
## *bsd/macos sed syntax#
sed ‘s/word1/word2/g’ input.file > output.file
sed -i ‘s/word1/word2/g’ input.file
sed -i -e ‘s/word1/word2/g’ -e ‘s/xx/yy/g’ input.file
## use + separator instead of / ##
sed -i ‘s+regex+new-text+g’ file.txt
The above replace all occurrences of characters in word1 in the pattern space with the corresponding characters from word2.
Examples that use sed to find and replace
Let us create a text file called hello.txt as follows:
$ cat hello.txt
The is a test file created by nixCrft for demo purpose.
foo is good.
Foo is nice.
I love FOO.
I am going to use s/ for substitute the found expression foo with bar as follows:
sed ‘s/foo/bar/g’ hello.txt
Sample outputs:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Please note that the BSD implementation of sed (FreeBSD/MacOS and co) does NOT support case-insensitive matching. You need to install gnu sed. Run the following command on Apple Mac OS:
$ brew install gnu-sed
######################################
### now use gsed command as follows ##
######################################
$ gsed -i ‘s/foo/bar/g I ‘ hello.txt
$ cat hello.txt
sed command problems
Consider the following text file:
$ cat input.txt
http:// is outdate.
Consider using https:// for all your needs.
Find word ‘http://’ and replace with ‘https://www.cyberciti.biz’:
sed ‘s/ http:// / https://www.cyberciti.biz /g’ input.txt
You will get an error that read as follows:
Our syntax is correct but the / delimiter character is also part of word1 and word2 in above example. Sed command allows you to change the delimiter / to something else. So I am going to use +:
sed ‘s+ http:// + https://www.cyberciti.biz +g’ input.txt
Sample outputs:
How to use sed to match word and perform find and replace
In this example only find word ‘love’ and replace it with ‘sick’ if line content a specific string such as FOO:
sed -i -e ‘/FOO/s/love/sick/’ input.txt
Use cat command to verify new changes:
cat input.txt
Recap and conclusion – Using sed to find and replace text in given files
The general syntax is as follows:
## find word1 and replace with word2 using sed ##
sed -i ‘s/word1/word2/g’ input
## you can change the delimiter to keep syntax simple ##
sed -i ‘s+word1+word2+g’ input
sed -i ‘s_word1_word2_g’ input
## you can add I option to GNU sed to case insensitive search ##
sed -i ‘s/word1/word2/gI’ input
sed -i ‘s_word1_word2_gI’ input
See BSD(used on macOS too) sed or GNU sed man page by typing the following command:
man sed
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
search and replace in files on linux (regex)
I have about 50 html files and need to search and replace image resizer urls in all of them
2:
remove : &mode=resizeByMinSize,cropToSize&cropPosition=topleft
3:
find : &width=
replace with : &w=
4:
find : &height=
replace with : &h=
5:
add this to end of the image url : &far=C&q=85&zc=C
edit:
output for this sample url should be :
/resizer/phpThumb.php?src=/uploads/images/5x6a6s9d7a9s7d8a9.jpg&w=64&h=64&far=C&q=85&zc=C
2 Answers 2
I’m going to assume your sample URL was missing a fragment in the middle. I think the following sed script might serve your needs:
There is probably a typo in your url above, in point 2 you say to remove &mode=resizeByMinSize,cropToSize&cropPosition=topleft but you forget to mention what to do with esizeByMinSize,cropToSize&cropPosition=topleft .
Anyway, the awk scrip below solves the problem: tweek it to your needs:
quoting is a bit messy, see awk-manual Wrap this in a find sequence and your problem is solved.
Not the answer you’re looking for? Browse other questions tagged regex search replace or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.8.40416
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
Unix Sed Tutorial: Find and Replace Text Inside a File Using RegEx
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.
- 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 REGEXP in a case-insensitive manner.
- w file If substitution was made, write out the result to the given file.
- We can use different delimiters ( one of @ % ; : ) instead of /
Let us first create thegeekstuff.txt file that will be used in all the examples mentioned below.
Let us review some interesting examples for substitution now.
1. Substitute Word “Linux” to “Linux-Unix” Using sed s//
In the example below, in the output line “1. Linux-Unix Sysadmin, Linux Scripting etc” only first Linux is replaced by Linux-Unix. If no flags are specified the first match of line is replaced.
2. Substitute all Appearances of a Word Using sed s//g
The below sed command replaces all occurrences of Linux to Linux-Unix using global substitution flag “g”.
3. Substitute Only 2nd Occurrence of a Word Using sed s//2
In the example below, in the output line “1. Linux Sysadmin, Linux-Unix Scripting etc.” only 2nd occurance of Linux is replaced by Linux-Unix.
4. Write Changes to a File and Print the Changes Using sed s//gpw
The example below has substitution with three flags. It substitutes all the occurance of Linux to Linux-Unix and prints the substituted output as well as written the same to the given the file.
5. Substitute Only When the Line Matches with the Pattern Using sed
In this example, if the line matches with the pattern “-“, then it replaces all the characters from “-” with the empty.
6. Delete Last X Number of Characters From Each Line Using sed
This sed example deletes last 3 characters from each line.
7. Eliminate Comments Using sed
Delete all the comment lines from a file as shown below using sed command.
8. Eliminate Comments and Empty Lines Using sed
In this example, there are two commands seperated by ‘;’
- First command replaces the lines starting with the # to the blank lines
- Second command deletes the empty lines.
9. Convert DOS newlines (CR/LF) to Unix format Using sed
Copy the DOS file to Unix, you could find \r\n in the end of each line.
This example converts the DOS file format to Unix file format using sed command.
10. Eliminate HTML Tags from file Using sed
In this example, the regular expression given in the sed command matches the html tags and replaces with the empty.
Источник
What GNU/Linux command-line tool would I use for performing a search and replace on a file?
What GNU/Linux command-line tool would I use for performing a search and replace on a file?
Can the search text, and replacement, be specified in a regex format?
4 Answers 4
GNU sed (which you probably have) is even more versatile:
Here is a brief explanation of those options:
-i[SUFFIX], —in-place[=SUFFIX] edit files in place (makes backup if extension supplied)
-r, —regexp-extended use extended regular expressions in the script.
The FreeBSD, NetBSD and OpenBSD versions also supports these options.
If you want to learn more about sed, Cori has suggested this tutorial.
Perl was invented for this:
Any normal s/// pattern in those single quotes. You can keep a backup with something like this:
But that’s really more sed’s job.
Consider Ruby as an alternative to Perl. It stole most of Perl’s one-liner commandline args ( -i , -p , -l , -e , -n ) and auto-sets $_ for you like Perl does and has plenty of regex goodness. Additionally Ruby’s syntax may be more comfortable and easier to read or write than Perl’s or sed’s. (Or not, depending on your tastes.)
perl -pi.bak -e ‘s/(foo|bar)/\U\1/g’ *.txt
In many cases when dealing with one-liners, performance isn’t enough of an issue to care whether you use lightweight sed or heavyweight Perl or heaveier-weight Ruby. Use whatever is easiest to write.
Источник
How can I replace a string in a file(s)?
Replacing strings in files based on certain search criteria is a very common task. How can I
- replace string foo with bar in all files in the current directory?
- do the same recursively for sub directories?
- replace only if the file name matches another string?
- replace only if the string is found in a certain context?
- replace if the string is on a certain line number?
- replace multiple strings with the same replacement
- replace multiple strings with different replacements
9 Answers 9
1. Replacing all occurrences of one string with another in all files in the current directory:
These are for cases where you know that the directory contains only regular files and that you want to process all non-hidden files. If that is not the case, use the approaches in 2.
All sed solutions in this answer assume GNU sed . If using FreeBSD or macOS, replace -i with -i » . Also note that the use of the -i switch with any version of sed has certain filesystem security implications and is inadvisable in any script which you plan to distribute in any way.
Non recursive, files in this directory only:
Recursive, regular files (including hidden ones) in this and all subdirectories
If you are using zsh:
(may fail if the list is too big, see zargs to work around).
Bash can’t check directly for regular files, a loop is needed (braces avoid setting the options globally):
The files are selected when they are actual files (-f) and they are writable (-w).
2. Replace only if the file name matches another string / has a specific extension / is of a certain type etc:
Non-recursive, files in this directory only:
Recursive, regular files in this and all subdirectories
If you are using bash (braces avoid setting the options globally):
If you are using zsh:
The — serves to tell sed that no more flags will be given in the command line. This is useful to protect against file names starting with — .
If a file is of a certain type, for example, executable (see man find for more options):
3. Replace only if the string is found in a certain context
Replace foo with bar only if there is a baz later on the same line:
In sed , using \( \) saves whatever is in the parentheses and you can then access it with \1 . There are many variations of this theme, to learn more about such regular expressions, see here.
Replace foo with bar only if foo is found on the 3d column (field) of the input file (assuming whitespace-separated fields):
(needs gawk 4.1.0 or newer).
For a different field just use $N where N is the number of the field of interest. For a different field separator ( : in this example) use:
Another solution using perl :
NOTE: both the awk and perl solutions will affect spacing in the file (remove the leading and trailing blanks, and convert sequences of blanks to one space character in those lines that match). For a different field, use $F[N-1] where N is the field number you want and for a different field separator use (the $»=»:» sets the output field separator to : ):
Replace foo with bar only on the 4th line:
4. Multiple replace operations: replace with different strings
You can combine sed commands:
Be aware that order matters ( sed ‘s/foo/bar/g; s/bar/baz/g’ will substitute foo with baz ).
or Perl commands
If you have a large number of patterns, it is easier to save your patterns and their replacements in a sed script file:
Or, if you have too many pattern pairs for the above to be feasible, you can read pattern pairs from a file (two space separated patterns, $pattern and $replacement, per line):
That will be quite slow for long lists of patterns and large data files so you might want to read the patterns and create a sed script from them instead. The following assumes a space > delimiter separates a list of MATCH space >REPLACE pairs occurring one-per-line in the file patterns.txt :
The above format is largely arbitrary and, for example, doesn’t allow for a space > in either of MATCH or REPLACE. The method is very general though: basically, if you can create an output stream which looks like a sed script, then you can source that stream as a sed script by specifying sed ‘s script file as — stdin.
You can combine and concatenate multiple scripts in similar fashion:
A POSIX sed will concatenate all scripts into one in the order they appear on the command-line. None of these need end in a \n ewline.
grep can work the same way:
When working with fixed-strings as patterns, it is good practice to escape regular expression metacharacters. You can do this rather easily:
5. Multiple replace operations: replace multiple patterns with the same string
Replace any of foo , bar or baz with foobar
A good replacement Linux tool is rpl, that was originally written for the Debian project, so it is available with apt-get install rpl in any Debian derived distro, and may be for others, but otherwise you can download the tar.gz file from SourceForge.
Simplest example of use:
Note that if the string contains spaces it should be enclosed in quotation marks. By default rpl takes care of capital letters but not of complete words, but you can change these defaults with options -i (ignore case) and -w (whole words). You can also specify multiple files:
Or even specify the extensions ( -x ) to search or even search recursively ( -R ) in the directory:
You can also search/replace in interactive mode with -p (prompt) option:
The output shows the numbers of files/string replaced and the type of search (case in/sensitive, whole/partial words), but it can be silent with the -q (quiet mode) option, or even more verbose, listing line numbers that contain matches of each file and directory with -v (verbose mode) option.
Other options that are worth remembering are -e (honor escapes) that allow regular expressions , so you can search also tabs ( \t ), new lines ( \n ),etc. You can use -f to force permissions (of course, only when the user has write permissions) and -d to preserve the modification times`).
Finally, if you are unsure what exactly will happen, use the -s (simulate mode).
Источник