
supongamos que este es mi archivo cuyo nombre es myFile1
1 10
2 20
3 30
4 40
5 50
6 60
Sé que quiero agregar mis otras columnas a esto. Esta columna está en el archivo myFile2.
10
11
12
13
14
15
16
. ¿Hay alguna forma de agregar myFile2 a myFile1 para crear esta tabla?
1 10 10
2 20 11
3 30 12
4 40 13
5 50 14
6 60 15
Respuesta1
paste
Es bastante útil aquí, pero te castigará si el número de valores no es igual:
$ paste -d' ' myFile{1,2}
1 10 10
2 20 11
3 30 12
4 40 13
5 50 14
6 60 15
16
Si desea limitar arbitrariamente las líneas utilizadas en el segundo archivo al primero, puede hacerlo, pero será un poco más lento y utilizará más RAM (no es que importe en un conjunto de datos tan pequeño).
$ paste -d' ' myFile1 <(head -n$(cat myFile1 | wc -l) myFile2)
1 10 10
2 20 11
3 30 12
4 40 13
5 50 14
6 60 15
Respuesta2
No pude resistirme a agregar la opción detallada (script en Python)
#!/usr/bin/env python3
with open("file1") as l:
l = [item.replace("\n", "") for item in l]
with open("file2") as l2:
l2 = [item.replace("\n", "") for item in l2]
for item in [l[i]+" "+l2[i] for i in range(0, len(l))]:
print(item)
>>>
1 10 10
2 20 11
3 30 12
4 40 13
5 50 14
6 60 15
>>>
Para escribir inmediatamente los cambios en el archivo1, el código sería:
#!/usr/bin/env python3
with open("file1", "r") as l:
l = [item.replace("\n", "") for item in l]
with open("file2", "r") as l2:
l2 = [item.replace("\n", "") for item in l2]
with open("file1", "wt") as edit:
for item in [l[i]+" "+l2[i] for i in range(0, len(l))]:
edit.write(item+"\n")
En caso de que también exista la posibilidad de que file2 tengamenosfilas que archivo1, el siguiente código se encarga de agregar correctamente la columna y de la posible adición de más columnas:
#!/usr/bin/env python3
with open("file1", "r") as l1:
l1 = [item.replace("\n", "") for item in l1]
with open("file2", "r") as l2:
l2 = [item.replace("\n", "") for item in l2]
for i in range(0, len(l1)):
try:
print(l1[i]+" "+l2[i])
except IndexError:
print(l1[i]+" ")