【问题标题】:Read content of file and put particular portion of content in separate files using bash使用 bash 读取文件内容并将特定部分内容放在单独的文件中
【发布时间】:2017-11-14 15:23:41
【问题描述】:

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

【问题讨论】:

  • 您误用了cat 命令。使用shellcheck 在此处发布之前检查您的代码。

标签: bash grep tail head


【解决方案1】:

使用单个 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

【讨论】:

    【解决方案2】:

    如果我理解正确:您有一个长文件 report.txt,并且您想从中提取短文件。每个文件的名称后跟文件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
    

    【讨论】:

    • 我不会像你一样把生成的文件写在/里,而是写在当前目录下。
    • 谢谢皮埃尔,你能接受这个问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    相关资源
    最近更新 更多