Friday, April 24, 2009

Edit file on linux using sed utility

With sed utility you can edit text inside file directly. It is not needed to open the file using any editor and then do editing task. sed is stream editor for filtering and transforming text.

Below is my student_grade.txt
# cat student_grade.txt
024401 4.98
024402 4.95
024403 4.95
024404 4.50
024405 4.95

Now using sed utility we will replace first few digits of "student_id" that is 0244 by "Roll:".

The syntax of using sed utility is,
sed {expression} {file}

Now using sed utility we want to replace "0244" with "Roll:"
# sed '/0244/s//Roll:/g' student_grade.txt
Roll:01 4.98
Roll:02 4.95
Roll:03 4.95
Roll:04 4.50
Roll:05 4.95

Let's now understand about the command.
within single quote,
/0244 indicates search for string 024434.
/s means substitute or replace work.
//Roll: means replace the word "0244" by "Roll:"
/g means make the changes global

Related Documents

No comments:

Post a Comment