4

if I have a file test.txt:

example 1 content 2013-3-8: hello java example 2 content 2013-4-9: hello c 

how can I use awk or sed to seperate the test.txt to two file

test1

hello java 

test2

hello c 

I use the command below:

awk '/example/{i++}{print > "test"i}' test.txt 

but it will remain the first line(example xxx), can I add some fragment to the print in awk to delete the first line?

7 Answers 7

6

You almost have it:

awk '/^example/ { i++; next } { print >"test"i}' 

the next makes awk skip the rest of the statements.

Sign up to request clarification or add additional context in comments.

Comments

2

You can use getline to skip the first line. The following should give the desired output:

awk '/example/{getline; i++}{print > "test"i}' test.txt 

Comments

1

Some weird way of doing this with sed:

sh <<< $(sed '/example/{N;s/\n//;s/example \([0-9]*\).*:\(.*\)/echo "\2" >> test\1;/}' input) 

Comments

1

This might work for you (GNU sed):

sed -ne '2~4w test1.txt' -e '4~4w test2.txt' test0.txt 

Comments

0

You could try something like :

awk 'BEGIN {i=0; j=0} /example/{i++; j=0} (j != 0){print > "test"i} {j++}' test.txt 

Comments

0
sed -n " /example 1/ {N;s/^.*\n// w test1.txt } /example 2/ {N;s/^.*\n// w test2.txt }" test.txt 

if you define a delimiter between section (define size or marker), there could be more text to put in each file

Comments

0

To complete the response from Alok Singhal: if you reach the "too many open files" limit on linux, you have to close the files in line.

awk '/^example/ {close("test" i); i++; next } { print >"test" i}' 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.