文件内容为:
1
name
linux
unix
---
he is
going to
learn
4
this is my
second difference
---
how to store
each difference in a variable
对于(number(1)和pattern“---”)之间的每个内容,我需要将值存储在数组中:之前和之后
例如: 在[0]
之前回显$name
linux
unix
在[0]
之后回显$he is
going to
learn
现在我们看到数字:4 现在我们需要移动数组的索引并将内容存储在其中。 在[1]
之前回显$this is my
second difference
在[1]
之后回显$how to store
each difference in a variable
我是shell的新手。你能帮帮我吗? 提前谢谢。
这是片段。
i=0;
while read line;
do
if grep '[0-9].*' == $line // checks if it starts with a digit
then
$line=$line+1 ( from the next line before " ---" store it in base )
while "$line" != "---"
$line=$line+1
do
base[$i]=$line
i=$(( i+1 ));
echo $base[$i]
done
fi
done <rit.log
echo "$base"
答案 0 :(得分:1)
#!/usr/bin/env bash
before=() after=()
del=$'\n' is_after=1 i=-1
while IFS= read -r line; do
[[ $line =~ ^[0-9]$ ]] && ((i++))
[[ $line =~ ^([0-9]+|---)$ ]] && { ((is_after=!is_after)); continue; }
if ((is_after)); then
after[i]+=$line$del
else
before[i]+=$line$del
fi
done < data
# trim the last delimiter
after=("${after[@]%?}")
before=("${before[@]%?}")