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

时间:2017-11-14 15:23:41

标签: bash grep tail head

我想从单个文件中获取特定文件并通过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

2 个答案:

答案 0 :(得分:2)

使用单个 awk 命令:

awk '/^Test[0-9] file content:/{ f=1; fn=tolower($1)".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

答案 1 :(得分:1)

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

这是我的解决方案:

#!/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