Linux replace one line

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:

  1. Use Stream EDitor (sed) as follows:
  2. sed -i ‘s/old-text/new-text/g’ input.txt
  3. The s is the substitute command of sed for find and replace
  4. It tells sed to find all occurrences of ‘old-text’ and replace with ‘new-text’ in a file named input.txt
  5. Verify that file has been updated:
  6. 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

Источник

Find and replace text within a file using commands

How can I find and replace specific words in a text file using command line?

7 Answers 7

  • 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’s multitude of ways to achieve it. Depending on the complexity of what one tries to achieve with string replacement, and depending on tools with which user is familiar, some methods may be preferred more than others.

In this answer I am using simple input.txt file, which you can use to test all examples provided here. The file contents:

Bash isn’t really meant for text processing, but simple substitutions can be done via parameter expansion , in particular here we can use simple structure $ .

This small script doesn’t do in-place replacement, meaning that you would have to save new text to new file, and get rid of the old file, or mv new.txt old.txt

Side note: if you’re curious about why while IFS= read -r ; do . done is used, it’s basically shell’s way of reading file line by line. See this for reference.

AWK, being a text processing utility, is quite appropriate for such task. It can do simple replacements and much more advanced ones based on regular expressions. It provides two functions: sub() and gsub() . The first one only replaces only the first occurrence, while the second — replaces occurrences in whole string. For instance, if we have string one potato two potato , this would be the result:

AWK can take an input file as argument, so doing same things with input.txt , would be easy:

Depending on the version of AWK you have, it may or may not have in-place editing, hence the usual practice is save and replace new text. For instance something like this:

Sed is a line editor. It also uses regular expressions, but for simple substitutions it’s sufficient to do:

What’s good about this tool is that it has in-place editing, which you can enable with -i flag.

Perl is another tool which is often used for text processing, but it’s a general purpose language, and is used in networking, system administration, desktop apps, and many other places. It borrowed a lot of concepts/features from other languages such as C,sed,awk, and others. Simple substitution can be done as so:

Like sed, perl also has the -i flag.

Python

This language is very versatile and is also used in a wide variety of applications. It has a lot of functions for working with strings, among which is replace() , so if you have variable like var=»Hello World» , you could do var.replace(«Hello»,»Good Morning»)

Simple way to read file and replace string in it would be as so:

With Python, however, you also need to output to new file , which you can also do from within the script itself. For instance, here’s a simple one:

Источник

How to replace an entire line in a text file by line number

I have a situation where I want a bash script to replace an entire line in a file. The line number is always the same, so that can be a hard-coded variable.

I’m not trying to replace some sub-string in that line, I just want to replace that line entirely with a new line.

Are there any bash methods for doing this (or something simple that can be thrown into a .sh script).

9 Answers 9

Not the greatest, but this should work:

where N should be replaced by your target line number. This replaces the line in the original file. To save the changed text in a different file, drop the -i option:

/’ $TCE_SVN_HOME\trunk\tce\EWC\WebContent\WEB-INF\web.xml . Any idea?

I actually used this script to replace a line of code in the cron file on our company’s UNIX servers awhile back. We executed it as normal shell script and had no problems:

This doesn’t go by line number, but you can easily switch to a line number based system by putting the line number before the s/ and placing a wildcard in place of the_original_line .

Let’s suppose you want to replace line 4 with the text «different». You can use AWK like so:

AWK considers the input to be «records» divided into «fields». By default, one line is one record. NR is the number of records seen. $0 represents the current complete record (while $1 is the first field from the record and so on; by default the fields are words from the line).

So, if the current line number is 4, print the string «different» but otherwise print the line unchanged.

In AWK, program code enclosed in < >runs once on each input record.

You need to quote the AWK program in single-quotes to keep the shell from trying to interpret things like the $0 .

EDIT: A shorter and more elegant AWK program from @chepner in the comments below:

Only for record (i.e. line) number 4, replace the whole record with the string «different». Then for every input record, print the record.

Clearly my AWK skills are rusty! Thank you, @chepner.

EDIT: and see also an even shorter version from @Dennis Williamson:

How this works is explained in the comments: the 1 always evaluates true, so the associated code block always runs. But there is no associated code block, which means AWK does its default action of just printing the whole line. AWK is designed to allow terse programs like this.

Источник

How to replace a string in multiple files in linux command line

I need to replace a string in a lot of files in a folder, with only ssh access to the server. How can I do this?

27 Answers 27

Occurrences of «foo» will be replaced with «bar».

On BSD systems like macOS, you need to provide a backup extension like -i ‘.bak’ or else «risk corruption or partial content» per the manpage.

Similar to Kaspar’s answer but with the g flag to replace all the occurrences on a line.

For global case insensitive:

@kev’s answer is good, but only affects files in the immediate directory.The example below uses grep to recursively find files. It works for me everytime.

grep -r: —recursive, recursively read all files under each directory.
grep -l: —print-with-matches, prints the name of each file that has a match, instead of printing matching lines.
grep -i: —ignore-case.

xargs: transform the STDIN to arguments, follow this answer.
xargs -i@

, the @ sign is a placeholder which could replaced by any string.

sed -i: edit files in place, without backups.
sed s/regexp/replacement/: substitute string matching regexp with replacement.
sed s/regexp/replacement/g: global, make the substitution for each match instead of only the first match.

There are a few standard answers to this already listed. Generally, you can use find to recursively list the files and then do the operations with sed or perl.

For most quick uses, you may find the command rpl is much easier to remember.

Replace foo with bar on all .txt files:

Simulate replacing the regex foo.* with bar in all .txt files recursively:

You’ll probably need to install it ( apt-get install rpl or similar).

repren

However, for tougher jobs that involve regular expressions and back substitution, or file renames as well as search-and-replace, the most general and powerful tool I’m aware of is repren, a small Python script I wrote a while back for some thornier renaming and refactoring tasks. The reasons you might prefer it are:

  • Support renaming of files as well as search-and-replace on file contents.
  • See changes before you commit to performing the search and replace.
  • Support regular expressions with back substitution, whole words, case insensitive, and case preserving (replace foo -> bar, Foo -> Bar, FOO -> BAR) modes.
  • Works with multiple replacements, including swaps (foo -> bar and bar -> foo) or sets of non-unique replacements (foo -> bar, f -> x).

To use it, pip install repren . Check the README for examples.

This worked for me:

Howerver, this did not: sed -i ‘s/string1/string2/g’ * . Maybe «foo» was not meant to be string1 and «bar» not string2.

To replace a string in multiple files you can use:

To replace a path within files (avoiding escape characters) you may use the following command:

The @ sign means that all of the special characters should be ignored in a following string.

Given you want to search for the string search and replace it with replace across multiple files, this is my battle-tested, one-line formula:

Quick grep explanation:

  • -R — recursive search
  • -i — case-insensitive
  • -I — skip binary files (you want text, right?)
  • -l — print a simple list as output. Needed for the other commands

The grep output is then piped to sed (through xargs) which is used to actually replace text. The -i flag will alter the file directly. Remove it for a kind of «dry run» mode.

In case your string has a forward slash(/) in it, you could change the delimiter to ‘+’.

This command would run recursively in the current directory.

The first line occurrences of «foo» will be replaced with «bar». And you can using the second line to check.

If you have list of files you can use

If you have all files you can use

If you have list of files with extension, you can use

«You could also use find and sed, but I find that this little line of perl works nicely.

  • -e means execute the following line of code.
  • -i means edit in-place
  • -w write warnings
  • -p loop

My best results come from using perl and grep (to ensure that file have the search expression )

On a MacBook Pro, I used the following (inspired by https://stackoverflow.com/a/19457213/6169225):

-i » will ensure you are taking no backups.

I did concoct my own solution before I found this question (and answers). I searched for different combinations of «replace» «several» and «xml,» because that was my application, but did not find this particular one.

My problem: I had spring xml files with data for test cases, containing complex objects. A refactor on the java source code changed a lot of classes and did not apply to the xml data files. In order to save the test cases data, I needed to change all the class names in all the xml files, distributed across several directories. All while saving backup copies of the original xml files (although this was not a must, since version control would save me here).

I was looking for some combination of find + sed , because it worked for me in other situations, but not with several replacements at once.

Then I found ask ubuntu response and it helped me build my command line:

And it worked perfectly (well, my case had six different replacements). But please note that it will touch all *.xml files under current directory. Because of that, and if you are accountable to a version control system, you might want to filter first and only pass on to sed those actually having the strings you want; like:

Источник

Читайте также:  Canon mf4410 драйвер для печати windows 10 64 bit
Оцените статью