五行关键字应该分割为6个文件啊?要不就是只取关键字行以下的行。
思路:用sed得出包含这个关键字的行的行号,然后根据行号分割文件。
#!/bin/sh
myFile=TestResult.txt
num=5
count=0
line=`sed -n '/FILE_TESTCASERESULT/=' $myFile`
for n in $line
do
[ $count -eq 0 ] && let startLine=n+1 && continue
let count+=1
let endLine=n-1
[ $count -eq $num ] && endLine=`sed -n '$=' myFile`
sed -n "${startLine},${endLine} p;q" $myFile >result_${count}.txt
let startLine=n+1
done
结果保存到result_1.txt,result_2.txt,result_3.txt,result_4.txt,result_5.txt五个文件中。
注:关键字行本身不保存。如果要保存关键字行,请修改代码中的 let startLine=n+1 为 startLine=$n (两处地方)。
追问我需要保存关键字行和关键字行下面的内容:我把您的代码按照你说的修改代码中的 let startLine=n+1 为 startLine=$n (两处地方)。
如果$line的值是 1 3 5 7,那么似乎这个程序有问题
追答我的脚本是基于你说的前提:有5行包含关键字的行。你看我的代码里也设了个前提:num=5
如果行数不确定,是需要修改代码的。下面这样应该可以:
#!/bin/sh
myFile=TestResult.txt
count=0
line=(`sed -n '/FILE_TESTCASERESULT/=' $myFile`) #Save in array
num=${#line[@]} #Get array size
for n in ${line[*]}
do
[ $count -eq 0 ] && startLine=$n && continue
let count+=1
let endLine=n-1
[ $count -eq $num ] && endLine=`sed -n '$=' myFile`
sed -n "${startLine},${endLine} p;q" $myFile >result_${count}.txt
let startLine=n+1
done
上面的脚本是基于你说的前提:有5行包含关键字的行。你看我的代码里也设了个前提:num=5
如果行数不确定,是需要修改代码的。下面这样应该可以了:
#!/bin/sh
myFile=TestResult.txt
count=0
line=(`sed -n '/FILE_TESTCASERESULT/=' $myFile`) #Save in array
num=${#line[@]} #Get array size
for n in ${line[*]}
do
[ $count -eq 0 ] && startLine=$n && continue
let count+=1
let endLine=n-1
if [ $count -eq $num ]; then
startLine=$n
sed -n "${startLine},$ p" $myFile >result_${count}.txt
else
sed -n "${startLine},${endLine} p;q" $myFile >result_${count}.txt
startLine=$n
fi
done
之前还有两处错误,有个myFile前面少了个$;startLine=$n 的位置也需要挪一下。
请用最后一个脚本。百度有问题,无法更新之前的回答而是直接显示到后面了。
追问第一次的file输出 count 1 startline:0,endline 0 不满足
且不知道为什么我这边报告说“[ $count -eq 0 ] && startLine=$n && continue” command not found
还有最后一部分的也是要存成一个文件谢谢
第一次的file输出 count 1 startline:0,endline 0 不满足
且不知道为什么我这边报告说“[ $count -eq 0 ] && startLine=$n && continue” command not found
还有最后一部分的也是要存成一个文件谢谢
追答你这边不支持continue关键字?那换一种方法:
#!/bin/sh
myFile=TestResult.txt
count=0
startLine=(`sed -n '/FILE_TESTCASERESULT/=' $myFile`)
fileEnd=`sed -n '$=' $myFile`
endLine=(`echo ${startLine[*]} | awk -v a=$fileEnd '{for(i=2;i<=NF;i++) printf("%d ",$i-1);print a}'`)
let maxIndex=${#startLine[@]}-1
for n in `seq 0 $maxIndex`
do
sed -n "${startLine[$n]},${endLine[$n]} p;q" $myFile >result_${n}.txt
done
startLine和endLine都存为数组,这样还简单些。
数组下标从0开始,所以,最大数组元素的下标(maxIndex)为数组长度减1。