3

From a certain number of files, I need to create a new file where each line of text is the sequence of the respective lines from my original files. So, let's say I have two files with a structure like this:

File1:

AAAA
BBBB
CCCC

File2:

XXXX
YYYY
ZZZZ

I need to combine them to get a result like:

AAAAXXXX
BBBBYYYY
CCCCZZZZ

How can I do this from a bash script?

3 Answers 3

9

Use the paste command:

paste -d '' File1 File2

By default, paste joins the lines with tabs, so we need to use the -d option to tell it to use the empty string for joining.

1
  • 2
    If this answer helps you, please accept it by clicking on the check mark.
    – PyGeek03
    Oct 23, 2016 at 17:26
2

Through way:

awk '{getline x<"file2"; print $0x}' file1
  • getline x<"file2" reads the entire line from file2 and holds into x variable.
  • print $0x prints the whole line from file1 by using $0 then x which is the saved line of file2.
1

paste is the way to go, but for the sake of completeness here is a bash focused solution (with little help from seq, and wc):

for _ in $(seq 1 $(wc -l <f1.txt)); do \
            read -u 3 one; read -u 4 two; echo "${one}${two}"; done 3<f1.txt 4<f2.txt

Here we are sending the contents of files f1.txt, and f2.txt via file descriptors 3, and 4. read reads from the respective FDs, and echo prints the output in desired format.

The iteration will stop after the f1.txt ends, here _ is a throwaway variable.


Better, just bash, depending on read's exit status when the EOF is reached, with a while construct (thanks to steeldriver):

while IFS= read -ru3 one && IFS= read -ru4 two; do echo "${one}${two}"; done 3<f1.txt 4<f2.txt

Example:

$ cat f1.txt
AAAA
BBBB
CCCC

$ cat f2.txt
XXXX
YYYY
ZZZZ

$ for _ in $(seq 1 $(wc -l <f1.txt)); do read -u 3 one; read -u 4 two; echo "${one}${two}"; done 3<f1.txt 4<f2.txt
AAAAXXXX
BBBBYYYY
CCCCZZZZ

$ while IFS= read -ru3 one && IFS= read -ru4 two; do echo "${one}${two}"; done 3<f1.txt 4<f2.txt
AAAAXXXX
BBBBYYYY
CCCCZZZZ
2
  • 1
    Wouldn't something like while IFS= read -ru3 a && IFS= read -ru4 b; do printf '%s%s\n' "$a" "$b"; done 3<File1 4<File2 terminate naturally upon exhaustion of either file (without requiring help from seq or wc)? Oct 23, 2016 at 22:07
  • @steeldriver It certainly would, edited, thanks for this one.
    – heemayl
    Oct 23, 2016 at 22:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .