i tried to do it using the if way, and i could only managed to do it using 3 lines. The execution time is definitely longer than your suggestion, since i have to open the file 3 times. Is there any way i can modify it into 1 line? I appreciate your 'for' loop, its elegant and achieves the purpose. But i am raw to UNIX script, hoping to learn more ways to do it.
awk 'BEGIN(FS="[:,]"} { if (NF == 3) print $1":"$2)' $F
awk 'BEGIN(FS="[:,]"} { if (NF == 3) print $1":"$3)' $F
awk 'BEGIN(FS="[:,]"} { if (NF == 2) print $1":"$2)' $F
Would appreciate if anyone can suggest?
i am looking at something like
awk 'BEGIN(FS="[:,]"} { if (NF == 3) print $1":"$2 \n print $1":"$3 \n else print $1":"$2 print)' $F
but i got a bunch of syntax errors.
awk: cmd. line:1: BEGIN{FS="[:,]"}{if (NF == 2)print $1":"$2\n}
awk: cmd. line:1: ^ backslash not last chine
bash> OIFS=$IFS; IFS=: ; while read name rest; do echo ${rest} | tr ',' '\n' | sed s/^/$name\:/g; done <your_data_filename; IFS=$OIFS
script1:
#!/usr/bin/bash
file=your_data_filename
for line in `cat $file`; do
name=`echo $line | cut -d':' -f1`
rest=`echo $line | cut -d':' -f2`
for i in `echo $rest | tr ',' ' '`; do
echo ${name}:${i}
done
done
script2:
#!/usr/bin/bash
file=your_data_filename
for line in `cat $file`; do
name=`echo $line | cut -d':' -f1`
rest=`echo $line | cut -d':' -f2`
echo $rest | tr ',' '\n' | sed s/^/$name\:/g
done
One small question thought, as i mentioned earlier, i am relatively new to scripting, how can i improve, to the extend i can come up with the one liners?
Will doing more scripting help or are there any references i can refer to ?