-1

i have two file like blow format and need to marge two file in below format (bash command)

1st row of 1st file + 1st row of 2nd file 2nd row of 1st file + 2nd row of 2nd file

Example :

file1

a
b
c
d

file2

1
2
3
4

expected output file

a,1
b,2
c,3
d,4
Cyrus
  • 84,225
  • 14
  • 89
  • 153

1 Answers1

0
#!/usr/bin/env bash

file1="$1"
file2="$2"

file1_contents=$(<"$file1")
file2_contents=$(<"$file2")

read -ra array1 <<< "$file1_contents"
read -ra array2 <<< "$file2_contents"

final_string=""
for ((i=0; i<"${#array1[@]}"; i++));
do
  final_string+="${array1[i]},${array2[i]} "
done

echo "$final_string"

This bash script reads 2 command line arguments, file1 and file2. Assuming file one has a b c d and file2 has 1 2 3 4 as their respective contents, then the script will read the contents of both files and convert the contents into an array using the read command. The -a option will make the read command convert the file1_contents into an array and store the result in the variable array1. It will do the same for the contents of the second file.

We then declare a final_string variable that will hold the final result. Afterwards we loop through the first array and on each iteration of the loop, we take the current element in the first array and concatenate it to the element at the same position of the second array and this we add to the final_string.

Hope it helps.

ismail pervez
  • 159
  • 2
  • 10
  • You don't need the `herestring`, and `command substitution` a simple redirection for reading the file should suffice, e.g. `read -ra array1 < file1; read -ra array2 < file2` – Jetchisel Jun 10 '23 at 08:51
  • thanks for the script but i found its only marge the file line only may be the loop not working – user2349201 Jun 10 '23 at 16:50