Indent line ranges with sed

Let's say you'd like to selectively indent line ranges in a file and would like to preview before making changes. Here's one way to do it with sed.

Before:

cat indent.test
1
2
3
4
5
6
7
8
#!/bin/bash
 
FooBar()
{
for l in a b c; do
 echo letter $l
done
}

I'd like to indent the code inside the function using a single space (e.g. insert a leading space in lines 5, 6 and 7).

Preview:

sed '5,7 s/^/ /' indent.test | sed -n 3,8p
FooBar()
{
 for l in a b c; do
  echo letter $l
 done
}

Note that I'm piping replacement sed to sed that will just print lines 3-8 (useful if you're working with a large file and don't want to scroll through hundreds of lines to preview the code your changes).

Apply:

sed -i '5,7 s/^/ /' indent.test

After:

cat indent.test
1
2
3
4
5
6
7
8
#!/bin/bash
 
FooBar()
{
 for l in a b c; do
  echo letter $l
 done
}

Leave a comment

NOTE: Enclose quotes in <blockquote></blockquote>. Enclose code in <pre lang="LANG"></pre> (where LANG is one of these).