Shell/Bash解析文本文件
我有一个文本文件,看起来像这样Shell/Bash解析文本文件,bash,shell,parsing,awk,text-processing,Bash,Shell,Parsing,Awk,Text Processing,我有一个文本文件,看起来像这样 Item: SubItem01 SubItem02 SubItem03 Item2: SubItem0201 SubItem0202 Item3: SubItem0301 ...etc... 我需要的是让它看起来像这样: Item=>SubItem01 Item=>SubItem02 Item=>SubItem03 Item2=>SubItem0201 Item2=>SubItem0202 Item3=>SubItem0301
Item:
SubItem01
SubItem02
SubItem03
Item2:
SubItem0201
SubItem0202
Item3:
SubItem0301
...etc...
我需要的是让它看起来像这样:
Item=>SubItem01
Item=>SubItem02
Item=>SubItem03
Item2=>SubItem0201
Item2=>SubItem0202
Item3=>SubItem0301
item_re="^(Item.*):$"
while read -r; do
if [[ $REPLY =~ $item_re ]]; then
item=${BASH_REMATCH[1]}
else
printf "%s=>%s\n" "$item" "$REPLY"
fi
done < file.txt
我知道这个事实,我需要两个for循环才能得到这个。我做了一些测试,但是。。。嗯,结果不太好
for(( c=1; c<=lineCount; c++ ))
do
var=`sed -n "${c}p" TMPFILE`
echo "$var"
if [[ "$var" == *:* ]];
then
printf "%s->" $var
else
printf "%s\n"
fi
done
for((c=1;c文本解析最好使用awk
:
$ awk '/:$/{sub(/:$/,"");h=$0;next}{print h"=>"$0}' file
Item=>SubItem01
Item=>SubItem02
Item=>SubItem03
Item2=>SubItem0201
Item2=>SubItem0202
Item3=>SubItem0301
如果你想继续沿着壳牌之路走下去,你可以这样做:
Item=>SubItem01
Item=>SubItem02
Item=>SubItem03
Item2=>SubItem0201
Item2=>SubItem0202
Item3=>SubItem0301
item_re="^(Item.*):$"
while read -r; do
if [[ $REPLY =~ $item_re ]]; then
item=${BASH_REMATCH[1]}
else
printf "%s=>%s\n" "$item" "$REPLY"
fi
done < file.txt
item_re=“^(item.*):$”
读的时候;做的时候
如果[[$REPLY=~$item\u re]];则
item=${BASH_重新匹配[1]}
其他的
printf“%s=>%s\n”“$item”“$REPLY”
fi
完成
使用awk
awk '/:/{s=$1;next}{print s OFS $0}' FS=: OFS="=>" file
下面是另一个awk
备选方案:
awk -F: '/^Item/{ITM=$1} !/^Item/{print ITM"=>"$0}'
如果行以“Item”开头,请将项目名称保存在ITM中。如果行不以“Item”开头,请打印以前保存的项目名称(ITM)、“=>”和子项目。打开拆分:可以更轻松地获取项目名称
假设子项组的前面总是有一个Item:entry,因此变量ITM应该始终具有当前组的名称。解决方案:
@(collect)
@left:
@ (collect)
@right
@ (until)
@(skip):
@ (end)
@(end)
@(output)
@ (repeat)
@ (repeat)
@left=>@right
@ (end)
@ (end)
@(end)
$ txr regroup.txr data.txt
Item=>SubItem01
Item=>SubItem02
Item=>SubItem03
Item2=>SubItem0201
Item2=>SubItem0202
Item3=>SubItem0301
不,你不需要两个循环。这是一个任务吗?我们有其他人也有同样的问题,不久前也有人错误地认为嵌套循环是正确的解决方案。谢谢,这可能正是我想要的!谢谢你的快速回复!谢谢你,我感谢你的帮助!确保我会这样做…如果我的repu回答太高了。你能解释一下吗?目前你的答案不完整。@bjb568我已经添加了一个解释。这有帮助吗?