0

I have file like this:

1 a,b,c
2 z
3 d,f

and would like to have this format:

1 a
1 b
1 c
2 z
3 d
3 f
  • 2
    what did you do so far ? did you get any errors ? If so, please provide your commands and the output you received. – MelBurslan Feb 9 '16 at 18:29
  • Are the values in the second column ever quoted (in order to contain a comma)? – Jeff Schaller Feb 9 '16 at 18:45
  • If any of the existing answers solves your problem, please consider accepting it via the checkmark. Thank you! – Jeff Schaller Apr 25 '17 at 10:37
1

Awk solution:

$ cat file
1 a,b,c
2 z
3 d,f

$ awk '{ gsub(",", "\n"$1" "); print; }' file
1 a
1 b
1 c
2 z
3 d
3 f
0

If your input is as simple as it looks, then here's a bash shell script doing the things that shell scripts are no good at:

#!/usr/bin/env bash
declare -a col2
while read col1 rest
do
  IFS=, read -a col2 <<< "$rest"
  for value in ${col2[*]}
  do
    printf "%s %s\n" "$col1" "$value"
  done
done < input

There are better ways to do it (read -a is bash-specific and not POSIX); there are other ways to do it (awk, perl). If your data is any more complicated (1 a,"b,c",d) or (1 a,b\,c,d) then this script will probably not do what you want.

0

Please try it:

sild@:/tmp $ cat test
1 a,b,c
2 z
3 d,f
sild@:/tmp $ cat test.sh 
#!/bin/bash
separator=","
cat test | while read line; do
 head="`echo $line | cut -d" " -f1`"
 IFS="$separator" read -ra nodes <<< "`echo $line | cut -d" " -f2-`"
 for i in "${nodes[@]}"; do
         echo $head $i
     done
 done
sild@:/tmp $ ./test.sh 
1 a
1 b
1 c
2 z
3 d
3 f
sild@:/tmp $ 
0

Perl solution :

perl -ane 'print map "$F[0] $_\n" ,split(",",$F[1])' file
1 a
1 b
1 c
2 z
3 d
3 f

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.