使用 bash 读取文件内容并将特定部分内容放在单独的文件中

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

我想从单个文件中获取特定文件包含并通过 bash 放入单独的文件中。我尝试使用以下代码获取包含 test1 文件并能够获取它,但是在获取相关文件中的所有内容时我失败了。

尝试过的代码:

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(预期):

1
2
3
4
5
6

test2.txt(预期):

7
8
9
10

test3.txt(预期):

11
12
13
14
15

如果我对您的理解正确:您有一个长文件 report.txt 并且您想从中提取短文件。每个文件的名称后跟字符串“file content:”在文件report.txt.

这是我的解决方案:

#!/bin/bash
reportFile=report.txt

Files=`grep 'file content' $reportFile | sed 's/ .*$//'`

for F in $Files ; do
    f=${F,}.txt         # first letter lowercase and append .txt
    awk "/$F file content/,/^$/ {print}" $reportFile |
        tail -n +2 |    # remove first line with "Test* file content:"
        head -n -1 > $f # remove last blank line
done

使用单个 awk 命令:

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

查看结果:

$ 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