新文件中的下一行以逗号分隔的单词

新文件中的下一行以逗号分隔的单词

我有一个像这样的输入文件(input.txt):

Main1 one,two,three,four 
Main2 five,six,seven,eight 

我想要在输出文件(output.txt)中得到这样的输出:

Main1 one
Main1 two
Main1 three
Main1 four

Main2 five
Main2 six
Main2 seven
Main3 eight

答案1

awk '{ split($2,a,","); for (i in a) print $1, a[i]; }' input.txt

例子:

~) $ echo -e "Main1 one,two,th\nMain2 five,six,seven,eight " | awk '{ split($2,a,","); for (i in a) print $1, a[i]; }'
Main1 one
Main1 two
Main1 th
Main2 five
Main2 six
Main2 seven
Main2 eight

答案2

以下是一些选择:

  1. while read main rest; do 
        for i in ${rest//,/$'\n'}; do 
            echo $main $i
        done
     done < file 
    
  2. Perl

    perl -lane 'print "$F[0] $_" for split(/,/,$F[1])' file
    
  3. awk

    awk -F'[, ]' '{for(i=2;i<=NF;i++){print $1,$i}}' file
    

相关内容