Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there's a way to do line by line combination of two files using bash shell [duplicate]

Tags:

bash

shell

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!

like image 657
Chris Avatar asked Mar 03 '17 22:03

Chris


People also ask

How do I merge two files line by line?

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.

How do I pass a file line by line in bash?

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.

How do you write a file line by line in shell script?

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.

How do you join two lines in bash?

A short Bash one-liner can join lines without a delimiter: $ (readarray -t ARRAY < input. txt; IFS=''; echo "${ARRAY[*]}") I cameI sawI conquered!


1 Answers

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')
like image 185
Charles Duffy Avatar answered Oct 08 '22 14:10

Charles Duffy