0

I have files like these:

$ cat A9E27.txt
person,42%
person,60%
$ cat ffn2eG6.txt
train,85%
$ cat sBHFgkv.txt  
person,85%
person,73%
chair,44%
person,57%
$ cat A8eVAmK.txt

etc etc Some of my txt files are actually even empty. how can I create a file that is like this

1,A9E27.txt,person,42%,person,60%
2,ffn2eG6.txt,train,85%
3,sBHFgkv.txt,person,85%,person,73%,chair,44%,person,57%
4,A8eVAmK.txt
5, etc etc 

where 1 shows the file number when I sort my file names alphabetically something like ls -1 | sort and A9E27.txt is the file name, and each line of file contents comes in front of it separated by comma

UPDATE: SchrodingersScat's answer from Ubuntu IRC is almost correct on stdout:

$ for i in * ; do echo -n "$i"; cat "$i" | sed ':a;$!{N;s/\n/, /;ba;}' ; done
5Co16.txtA9E27.txtperson,42%, person,60%
ffn2eG6.txttrain,85%
Kkc4e.txtsBHFgkv.txtperson,85%, person,73%, chair,44%, person,57%

gives correct answer but how can I save this result shown on stdout into a file correctly?

  • for ...; done > output.txt – muru Oct 28 '16 at 2:50
  • that produced results that did not make sense – Mona Jalal Oct 28 '16 at 2:58
  • Your own answer does the same thing. – muru Oct 28 '16 at 2:59
1

kerframil from bash IRC:

$  i=1; for f in *; do [[ -f $f ]] || continue; data=$(tr '\n' ',' < "$f"); printf '%s,%s,%s\n' "$((i++))" "$f" "${data%,}"; done > ../../in-your-file-correctly.txt

notes:

/join #bash 
1

How about using perl in slurp mode?

$ perl -F'\n' -0777ne 'print join(",", ++$n, $ARGV, @F), "\n"' *.txt
1,A8eVAmK.txt
2,A9E27.txt,person,42%,person,60%
3,ffn2eG6.txt,train,85%
4,sBHFgkv.txt,person,85%,person,73%,chair,44%,person,57%

Note that the shell *.txt glob causes the files to be processed in the default collation order of your locale - that might not be what you consider to be "alphabetic" (although it should be the same as that produced by ls -1, I think).

To save the result to a file, redirect it:

perl -F'\n' -0777ne 'print join(",", ++$n, $ARGV, @F), "\n"' *.txt > somefile

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.