We can use sed with w option to split a file into mutiple files. Files can be split by specifying line address or pattern.

suggest change

Suppose we have this source file that we would like to split:

cat -n sourcefile

*1 On the Ning Nang Nong

2 Where the Cows go Bong!

3 and the monkeys all say BOO!

4 There’s a Nong Nang Ning

5 Where the trees go Ping!

6 And the tea pots jibber jabber joo.

7 On the Nong Ning Nang*

Command to split the file by line number:

sed '1,3w f1
> 4,7w f2' sourcefile

This writes line1 to line3 into file f1 and line4 to line7 into file f2, from the sourcefile.

cat -n f1

*1 On the Ning Nang Nong

2 Where the Cows go Bong!

3 and the monkeys all say BOO!*

cat -n f2

1 There’s a Nong Nang Ning

2 Where the trees go Ping!

3 And the tea pots jibber jabber joo.

4 On the Nong Ning Nang

Command to split the file by context/pattern:

sed '/Ning/w file1
> /Ping/w file2' sourcefile

This splits the sourcefile into file1 and file2. file1 contains all lines that match Ning, file2 contains lines that match Ping.

cat file1

*On the Ning Nang Nong

There’s a Nong Nang Ning

On the Nong Ning Nang*

cat file2

Where the trees go Ping!

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents