根据特定模式

时间:2017-03-24 11:00:23

标签: bash unix

我有一个这样的输入文件:

输入.txt:

*******************************************************************
**
**
**
**
**  report ID: COBX COLLIATERAL IN MARGINX MEMO REPORT
**
**
**
***********************************************************************
ehwq
A
s
fdf
fg
gfdg
fgfd

*******************************************************************
**
**
**
**
**  REPORT ID : CZXC COLLATREAL ACTVTY BY CRD
**
**
**
***********************************************************************
ain lik
fklhsdk
dgfjkdghdfkj
dgfdjhgkjdf
fgjhfkjdghfkjd
fg
jdfkhgkjdfh

当我运行脚本时,输出应该分成多个文件,如下所示:

文件1:

*******************************************************************
**
**
**
**
**  report ID: COBX COLLIATERAL IN MARGINX MEMO REPORT
**
**
**
***********************************************************************
ehwq
A
s
fdf
fg
gfdg
fgfd

文件2:

*******************************************************************
**
**
**
**
**  REPORT ID : CZXC COLLATREAL ACTVTY BY CRD
**
**
**
***********************************************************************
ain lik
fklhsdk
dgfjkdghdfkj
dgfdjhgkjdf
fgjhfkjdghfkjd
fgjdfkhgkjdfh

我尝试过:

grep -i "report id" $1 > ./pattern.txt j=head -1 pattern.txt;
echo "first line is : - $j";
count=0;
name="output";
sed -n '2,$p' pattern.txt > pattern_1.txt while read i do count=expr $count + 1;
line=echo "$i";
echo "line is --- $i -- end";
sed -n '/'"$j"'/,/'"$line"'/ {/'"$line"'/d;p;}' $1 > ${name}_${count}.txt;
j=`echo "$line";
sed -i '1i\ ************************************************************‌​*******\ **\ **\ **\ ** ' ${name}_${count}.txt;
done < pattern_1.txt last_pattern=tail -1 pattern.txt`;
sed -n '/'"$last_pattern"'/,$ {p;}' $1 > ${name}_last.txt;
sed -i '1i\ ************************************************************‌​*******\ **\ **\ **\ ** ' ${name}_last.txt;

1 个答案:

答案 0 :(得分:0)

我认为这是最好的方法,但我假设每个块后文件中都会有一个空行,如您发布的示例所示:

i=0;
while read line
do
     printf "$line\n" >> splitted_part_${i}.txt
     if [ $( echo "$line" | grep -e "^[ ]*$" | wc -l ) -gt 0 ] 
     then 
           (( i++ ))
     fi
done <<< "$( cat input.txt )"

每次遇到新的EMPTY行时,我都会创建一个新文件。 在您的示例中,第18行和第36行为空:

bash-4.1$ grep -n -e "^[ ]*$" input.txt
18:
36:

希望这适合你。让我知道。