2

Example: File name: ENSG00000000003

ENSG00000000003 43120.829491094
ENSG00000000005 39604.4956791524
ENSG00000000419 7645.05624570546
ENSG00000000457 2157.49855156382
ENSG00000000460 3317.98417717746
ENSG00000000938 6327.40515535397

Expected output; ideally, the filename is preceded by a tab:

    ENSG00000000003
ENSG00000000003 43120.829491094
ENSG00000000005 39604.4956791524
ENSG00000000419 7645.05624570546
ENSG00000000457 2157.49855156382
ENSG00000000460 3317.98417717746
ENSG00000000938 6327.40515535397

I want to do this in loop for my 45000 files together

7

I would use the standard UNIX editor (of course!):

for f in ENSG*
do
  printf '1i\n\t%s\n.\nw\nq\n' "$f" | ed -s "$f"
done

This sends a small script of commands to ed, namely:

  • at line 1, insert (i) some text; the text is passed through printf as the filename, preceded by a tab (\t)
  • after inserting that text (.), save the file to disk (w) and quit (q)

If, indeed, the number of files exceeds the command-line limit, then you could use a find command; adjust the parameters (starting directories, filenames, etc) as needed:

find . -name 'ENSG*' -exec sh -c 'printf "1i\n\t%s\\n.\nw\nq\n" "$1" | ed -s "$1" ' findsh {} \;

The core solution is the same, but wrapped in what I call a "find shell" -- find executes sh -c ... for each (single) filename that matches; the findsh string is a stub name for $0 and the filename is passed to that shell in place of the {} curly braces. The shell itself then has the filename as parameter $1, so that's what the printf and ed commands use.

|improve this answer|||||
  • 1
    +1 for using ed, man! – Jim L. May 13 '19 at 21:30
3

Alternatively, still using ed, with zsh, a single invocation and no command-line limit (length or number of arguments):

printf 'e %s\n1i\n\t%1$s\n.\nw\nq\n' * | ed

(zsh’s printf supports %m$ specifiers to re-use arguments.)

|improve this answer|||||

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.