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.

How to print a file by line range using sed?

Answer:

In a given file, if you want to print out, say line 340-350, is easy with sed:

# sed -n '340,350p' text.txt

Remove specified lines from a file using sed

Answer:

Assume your have a file text.txt contains 100 lines, if you want to remove the lines 20-30, what you need is sed:

# sed '20,30d' text.txt

That's is easy.

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&/'

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.

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