Search code examples
bashgreptailhead

Read content of file and put particular portion of content in separate files using bash


I would like to get specific file contains from single file and put into separate files via bash. I have tried getting test1 file contain using below code and able to get it but i'm failed when getting everything in respected files.

Tried code:

reportFile=/report.txt
test1File=/test1.txt
test2File=/test2.txt
test3File=/test3.txt

totalLineNo=`cat ${reportFile} | wc -l`
test1LineNo=`grep -n "Test1 file content :" ${reportFile} | grep -Eo '^[^:]+'`
test2LineNo=`grep -n "Test2 file content :" ${reportFile} | grep -Eo '^[^:]+'`
test3LineNo=`grep -n "Test3 file content :" ${reportFile} | grep -Eo '^[^:]+'`

exactTest1LineNo=`echo $(( ${test1LineNo} - 1 ))`
exactTest2LineNo=`echo $(( ${test2LineNo} -1 ))`
exactTest3LineNo=`echo $(( ${test3LineNo} -1 ))`

test1Content=`cat ${reportFile} | head -n ${exactTest1LineNo}`
test3Content=`cat ${reportFile} | tail -n ${exactTest3LineNo}`

echo -e "${test1Content}\r" >> ${test1File}
echo -e "${test3Content}\r" >> ${test3File}

report.txt:

-------------------------------------

My Report:

Test1 file content:
1
2
3
4
5
6

Test2 file content:
7
8
9
10

Test3 file content:
11
12
13
14
15

Note: Find my report above.

-------------------------------------

test1.txt (expected):

1
2
3
4
5
6

test2.txt (expected):

7
8
9
10

test3.txt (expected):

11
12
13
14
15

Solution

  • With single awk command:

    awk '/^Test[0-9] file content:/{ f=1; fn=tolower($1)".txt"; next }
         f && NF{ print > fn }!NF{ f=0 }' report.txt 
    

    Viewing results:

    $ head test[0-9].txt
    ==> test1.txt <==
    1
    2
    3
    4
    5
    6
    
    ==> test2.txt <==
    7
    8
    9
    10
    
    ==> test3.txt <==
    11
    12
    13
    14
    15