PDA

View Full Version : format list to table (bash)


FFUser
31st May 2009, 10:06 PM
Hi -

Having gotten a little forgetful, and not successful in Googling the answer, I do not immediately recall how to reformat a list (let's say from stdin) to a table (on stdout).

For the sake of an example, I'd like to pipe the following input:

Item_1_1
Item_1_2
Item_1_3
Item_2_1
Item_2_2
Item_2_3

to a command which generates:

Item_1_1;Item_1_2;Item_1_3
Item_2_1;Item_2_2;Item_2_3


I seem to recall it is a function in the groff/ troff suite, but could be wrong. I appreciate the help.

Thanks.

livibetter
31st May 2009, 11:19 PM
I don't know about groff, but awk should do the work well:
foo | awk 'ORS=NR%3?",":"\n"'

FFUser
31st May 2009, 11:46 PM

Works great. Thanks!

RupertPupkin
1st June 2009, 01:18 AM
I don't know about groff, but awk should do the work well:
foo | awk 'ORS=NR%3?",":"\n"'
That works in the special case when the items occur in threes. If you had input like this:
Item_1_1
Item_1_2
Item_1_3
Item_1_4
Item_2_1
Item_2_2
Item_3_1
Item_3_2
Item_3_3
Item_4_1
it wouldn't work. But piping the input to this bash script (tableformat.sh) would work in all cases:
#!/bin/bash
N=1
OUTPUT=""
while read line
do
if [[ "${line}" = Item_${N}_* ]]; then
OUTPUT="${OUTPUT}${line};"
else
echo "${OUTPUT%;}"
((N=N+1))
OUTPUT="${line};"
fi
done
if [[ "${OUTPUT}" = *\; ]]; then
echo "${OUTPUT%;}"
fi
$ pipe_your_input | tableformat.sh
Item_1_1;Item_1_2;Item_1_3;Item_1_4
Item_2_1;Item_2_2
Item_3_1;Item_3_2;Item_3_3
Item_4_1

ghostdog74
1st June 2009, 04:50 AM
if you have Python

#!/usr/bin/env python
d={}
for line in open("file"):
oline=line.strip()
line=oline.split("_")
key=''.join(line[:2])
d.setdefault(key,[])
d[key].append(oline)
for k in sorted(d.keys()):
print ','.join(d[k])

output

# ./test.py
Item_1_1,Item_1_2,Item_1_3,Item_1_4
Item_2_1,Item_2_2
Item_3_1,Item_3_2,Item_3_3
Item_4_1