Home > other >  Paste text with the order of directory
Paste text with the order of directory

Time:09-27

I have a directory with 50 subdirectories that looks like this:

DIR -
     | dir1
     | dir2
     | dir...
     | dir49
     | dir50

Within each subdirectory, I have the two files with the same name

dir1 -
      |fileA.tsv
      |fileB.tsv

Now I want to paste dir*/fileA.tsv column wise; which can be achieved with

paste -d "\t" dir*/fileA.tsv > fileA_All.tsv

But the issue is the pasting order is wrong: it seems it’s pasting with this order:

dir1/fileA.tsv
dir10/fileA.tsv
dir11/fileA.tsv
...

Is there an approach to paste files with numerical order?

CodePudding user response:

Try:

# Lists all dirs on separate lines.
printf "%s\n" dir*/fileA.tsv |
# This is HAHA-tricky. The separator is _the letter_ 'r'.
# We sort using the _second field_ numerically.
sort -tr -k2n |
xargs -d '\n' paste -d '\t' > fileA_All.tsv

To be pro, use zero separated streams: printf "%s\0" ... sort -z ... xargs -0.

CodePudding user response:

You can try this:

paste dir{?,??}/fileA.tsv >fileA_All.tsv

dir{?,??} will expand first single digit directories and then two-digit ones (with dir prefix).

  • Related