Linux Ask!

Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.

Apr 112010
 

Insert search string back to the result in sed

Answer:

Following command will replace "foo" by "bar", using the sed.

# echo "foo" | sed 's/foo/bar/'

But how to append the word "foo" at the end of "bar"?

Here is the solution with the & (& defines the pattern found in the search string)

# echo "foo" | sed 's/foo/bar&/'

Mar 092010
 

Speedup sed search and replace

Answer:

If you have a very large file, sometimes you can speed up sed by using the following method:

Original method:

# sed 's/foo/bar/g' filename

Optimized method:

# sed '/foo/ s/foo/bar/g' filename

The second method is faster since substitution is only performed when the search string is found.

Feb 082010
 

sed: replace in place

Answer:

Newer version of sed allow you replace a file in place, no more redirection is needed.

# sed -i 's/abc/def/g' test.txt

The above command will replace all "abc" to "def" in the file test.txt