简体   繁体   中英

Merge one-line texts into a data-frame with basic ubuntu shell commands

I have let's say two files Input1.txt and Input2.txt . Each of them is a text file containing a single line of 5 numbers separated by a tab.

For instance Input1.txt is

1 2 3 4 5

and Input2.txt is

6 7 8 9 10

The output that I desire is Output.txt :

Input1 1 2 3 4 5
Input2 6 7 8 9 10

So I want to merge the files in a table with an extra first column containing the names of the original files. Obviously I have more than 2 files (actually 1000) and I would like to make it with a for loop. You can assume that all my files are named as Input*.txt with * between 1 and 1000 and that they are all in the same directory.

I know how to do it with R, but I would like to make it with a basic line of commands in the ubuntu shell. Is it feasible? Thanks for any help.

Assuming the line in Input1.txt , Input2.txt , etc. is terminated with a newline character, you can use

for i in Input*.txt
do
    printf "%s " "$i"
    cat "$i"
done > Output.txt

The result is

Input1.txt 1 2 3 4 5
Input2.txt 6 7 8 9 10

If you want to get Input1 etc. without .txt you can use

    printf "%s " "${i%.txt}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM