Split files based on file content and pattern matching

前端 未结 6 2087
执笔经年
执笔经年 2020-12-15 22:45

I need your help with formate a txt file using bash/linux. The file looks like the following, it always has a line called Rate: Sth then it follows with the details in the v

6条回答
  •  长情又很酷
    2020-12-15 22:56

    (g)awk to the rescue:

    awk '/^Rate:/ {output_file_name=$2; getline } 
         { print $0 >> ( output_file_name ) }' INPUT_FILE
    

    The first rule and command executes for the lines that starts with Rate: and only sets the output file name, then gets the next line from the input file. Then this next line is processed and gets written to the output file. After that the next line is processed by only the second command (gets written to the output file), but only if it not matches Rate:.

    NOTE: The above solution might fail if there is a section in the input file with two continuous lines of Rate:s, like this:

    ... DATA ...
    Rate: GBP
    Rate: CHF
    ... DATA ...
    

    should do (assuming that the line numbers are not part of the original file).

    HTH

提交回复
热议问题