2

I have text file contain strings like this

abc,def,ghi,jkl,mno,pqr,stu,wxyz

I want to make it like this

1.abc
2.def
3.ghi
4.jkl
5.mno
6.pqr
7.stu
8.wxyz

how can i do that using sed?

2
  • Related: unix.stackexchange.com/questions/222218/… Oct 10 '18 at 12:49
  • 1
    You say "strings" (plural). Can you give a larger example of the input file and what the output should look line? I'm assuming there could be multiple lines of these strings and that each should either be enumerated individually or as part of the overall sequence of entries.
    – Kusalananda
    Oct 10 '18 at 13:36
7

You can do this

echo abc,def,ghi,jkl,mno,pqr,stu,wxyz  | sed 's/,/\n/g' | nl -s "."

     1.abc
     2.def
     3.ghi
     4.jkl
     5.mno
     6.pqr
     7.stu
     8.wxyz
0
6

You can use GNU awk:

awk -v RS=',|\n' '{printf "%s.%s\n",NR,$0}' <<< "abc,def,ghi,jkl,mno,pqr,stu,wxyz"
1

A couple of Perl approaches:

$ perl -F, -lne 'print ++$k.".$_" for @F' file
1.abc
2.def
3.ghi
4.jkl
5.mno
6.pqr
7.stu
8.wxyz

$ perl -pne 'chomp;s/([^,]+),*/++$k.".$1\n"/ge' file
1.abc
2.def
3.ghi
4.jkl
5.mno
6.pqr
7.stu
8.wxyz

And awk:

$ awk -F, '{for(i=1;i<=NF;i++){print i"."$i}}' file
1.abc
2.def
3.ghi
4.jkl
5.mno
6.pqr
7.stu
8.wxyz
0
$ <file sed 's/,/\n/g' | sed '=' | paste -d . - -

1.abc
2.def
3.ghi
4.jkl
5.mno
6.pqr
7.stu
8.wxyz

Your Answer

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