我有一个格式为的属性文件
group1=A,B,C
group1_count=10
# zero or more number of empty lines
group2=A,E
group2_count=1
...
...
我想在bash脚本中读取该文件,并打印类似以下内容:group_name:group_count
group1:10:A,B,C
group2:1:A,E
如果您的输入是排序的(不需要对无序显示的项进行分组——这将调用bash 3不支持的数据结构(,您可以执行以下操作:
#!/usr/bin/env bash
name=
while IFS= read -r line; do
[[ $line = *"#"* ]] && line=${line%%"#"*} # strip comments
[[ $line ]] || continue # skip empty lines
[[ $line =~ ^[[:space:]]+$ ]] && continue # skip lines with only whitespace
new_name=${line%%_*}; new_name=${new_name%%=*}
if [[ $new_name != "$name" ]]; then
if [[ $name ]]; then
echo "${name}:${count}:${groups}"
fi
name=$new_name; count=; groups=
fi
case $line in
*_count=*) count=${line#*_count=} ;;
*=*) groups=${line#*=} ;;
esac
done
echo "${name}:${count}:${groups}"
在上查看此运行https://ideone.com/nrpfLO
您也可以尝试此awk
:
awk -F= -v OFS=: 'NF!=2 {next} sub(/_count$/, "", $1)
{print $1, $2, grp[$1]} {grp[$1] = $2}' file
group1:10:A,B,C
group2:1:A,E
在Mac上,默认情况下应该有ed
。
script.ed
g/^$/d
g/./+1s/.*=(.*)/ 1/
g/./;+1j
s/^([^=]*)([^ ]*)(.*)$/132/
s/[= ]/:/g
,p
Q
现在运行
ed -s file.txt < script.ed