Select certain column of each file, paste to a new file
with paste
under bash you can do:
paste <(cut -f 4 1.txt) <(cut -f 4 2.txt) .... <(cut -f 4 20.txt)
With a python script and any number of files (python scriptname.py column_nr file1 file2 ... filen
):
#! /usr/bin/env python
# invoke with column nr to extract as first parameter followed by
# filenames. The files should all have the same number of rows
import sys
col = int(sys.argv[1])
res = {}
for file_name in sys.argv[2:]:
for line_nr, line in enumerate(open(file_name)):
res.setdefault(line_nr, []).append(line.strip().split('\t')[col-1])
for line_nr in sorted(res):
print '\t'.join(res[line_nr])
The following script does this using awk. I have added for convenience a rownumber, which indicates the number of rows in your files (r). The number of columns you'd like to paste is indicated by c.
directory=/your-directory/
r=4
c=20
for n in $(seq 1 $r); do
echo "$n" >> rownumber.txt
done
for n in $(seq 1 $c); do
awk '{ print $4}' /$directory/file-$n.txt > /$directory/output-$n.txt
done
paste /$directory/rownumber.txt /$directory/output-[1-$c]*.txt > /$directory/newfile.txt