What can be used in command line to replace a line starting with "something" in a text file.

Posted on 2006-10-31
Last Modified: 2010-04-21
I have a text file that looks something like this:

118 => some text …
120 => some text …
121 => some text …
130 => some text …

What I’m trying to do is to replace a line starting with lets say “120” with different text for example “120 => some other text”.  Is there an easy way to do this, perhaps with sed, and what would the command look like.

Question by:kasiencja
  • 3
  • 2
LVL 48

Expert Comment

ID: 17845565
sed "s/120 =>.*/120 => some other text/" file >newfile
LVL 48

Accepted Solution

Tintin earned 500 total points
ID: 17845576
or to be a little stricter

sed "s/^120 =>.*/120 => some other text/" file >newfile

The ^ means start of line

Author Comment

ID: 17845658
Is it possible to make the changes within the same file, instead of having to write to a newfile?

LVL 48

Expert Comment

ID: 17845834
Depends on your Unix/Linux version.  If your sed version has the -i flag, you can do

sed -i "s/^120 =>.*/120 => some other text/" file

if not you can do

sed "s/^120 =>.*/120 => some other text/" file >/tmp/$$ && mv /tmp/$$ file

or you can use perl

Author Comment

ID: 17845867
Awesome! Thanks!

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java performance on Solaris - Managing CPUs There are various resource controls in operating system which directly/indirectly influence the performance of application. one of the most important resource controls is "CPU".   In a multithreaded…
Why Shell Scripting? Shell scripting is a powerful method of accessing UNIX systems and it is very flexible. Shell scripts are required when we want to execute a sequence of commands in Unix flavored operating systems. “Shell” is the command line i…
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
In a previous video, we went over how to export a DynamoDB table into Amazon S3.  In this video, we show how to load the export from S3 into a DynamoDB table.

820 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question