在文件中查找表达式,处理内容直到UNIX中循环中表达式的下一次出现

时间:2017-01-03 02:59:33

标签: loops unix

输入文件是:

ABC 
line1
line2
line3
ABC
line3
line2
ABC
line1

在这里,我想在unix中使用循环,并在获得单词ABC之后处理每个部分,直到下一次出现ABC

3 个答案:

答案 0 :(得分:0)

不是很清楚,但这里有一些可以帮助的东西,一个bash脚本:

export flag=0; cat txt.txt |while read oneline; do 
  echo $oneline; 
  if [ "$oneline" = "ABC" ]; then 
    echo "Trig, flag=$flag"; 
    let flag=(1-$flag); 
  else 
    echo "process: $oneline"; 
  fi; 
done

输出是:

ABC
Trig, flag=0
line1
process: line1
line2
process: line2
line3
process: line3
ABC
Trig, flag=1
line3
process: line3
line2
process: line2
ABC
Trig, flag=0
line1
process: line1

当然,不知道“处理”线条是什么意思,我只是用一个标记来记住状态,然后使用“echo $ oneline”来模拟这个过程。

答案 1 :(得分:0)

您可以尝试如下。

此处,每个循环迭代中的临时文件中都提供了所需的数据。根据需要进行处理。

文件名是:test.txt

line_array=$(grep -nw ABC test.txt | awk -F":" '{print $1 }')

for range in `awk '{ a[++i]=$0;} END { for (key in a) {print a[key]","a[key+1];}}' <<< "$line_array"`; do echo "BLOCK START" ; range_start=`awk -F"," '{ print $1}' <<< "$range"`; range_start=$(( $range_start + 1 )); range_end=`awk -F"," '{ print $2}' <<< "$range"`;  if [ ! -z ${range_end} ] ;then range_end=$(( $range_end - 1 ))  ;fi ;range=$range_start","$range_end ; range=$(sed 's/,$/,\$/g' <<< "$range") ;  sed -n "${range}p" test.txt > temp; cat temp; echo "BLOCK END" ;done

输出:

BLOCK START
line1
line2
line3
BLOCK END
BLOCK START
line3
line2
BLOCK END
BLOCK START
line1
BLOCK END

答案 2 :(得分:0)

马修斯何塞的好答案!! 如果您愿意,我还有另一种选择

我将您的内容用作&#34;虚拟文件&#34;,您可以在此处使用您的实际文件名。

for value in $(cat dummyfile |perl -p -e 's/\n/,/' | sed -e 's/ //g' -e 's/ABC,/ /g' -e 's/, / /g' -e 's/,$//g')
do
     echo "EXECUTION START"
     for innerloop in $(echo ${value} | sed 's/,/ /g')
     do
              # DO YOUR CALCULATIONS HERE
              echo $innerloop
     done
     echo "EXECUTION STOP"
done

输出:

EXECUTION START
line1
line2
line3
EXECUTION STOP
EXECUTION START
line3
line2
EXECUTION STOP
EXECUTION START
line1
EXECUTION STOP