Please see example: Let's say I have File1.txt with three lines(a,b,c); File 2 also has 3 lines(1,2,3).
File1
a
b
c
File 2
1
2
3
...
I want to get A File3 like following:
File 3
a1
a2
a3
b1
b2
b3
c1
c2
c3
...
Many thanks!
To merge files line by line, you can use the paste command. By default, the corresponding lines of each file are separated with tabs. This command is the horizontal equivalent to the cat command, which prints the content of the two files vertically.
The syntax is as follows for bash, ksh, zsh, and all other shells to read a file line by line: while read -r line; do COMMAND; done < input. file.
Using '>>' with 'echo' command appends a line to a file. Another way is to use 'echo,' pipe(|), and 'tee' commands to add content to a file.
A short Bash one-liner can join lines without a delimiter: $ (readarray -t ARRAY < input. txt; IFS=''; echo "${ARRAY[*]}") I cameI sawI conquered!
Assuming bash 4.x:
#!/usr/bin/env bash
# ^^^^-- NOT /bin/sh
readarray -t a <file1 # read each line of file1 into an element of the array "a"
readarray -t b <file2 # read each line of file2 into an element of the array "b"
for itemA in "${a[@]}"; do
for itemB in "${b[@]}"; do
printf '%s%s\n' "$itemA" "$itemB"
done
done
On an older (pre-4.0) release of bash, you can replace readarray -t a <file1
and readarray -t b <file2
with:
IFS=$'\n' read -r -d '' -a a < <(cat -- file1 && printf '\0')
IFS=$'\n' read -r -d '' -a b < <(cat -- file2 && printf '\0')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With