1

I have 2 files: /tmp/first.txt and /tmp/last.txt

cat /tmp/first.txt
john
adam
max

cat /tmp/last.txt
smith
moore
caviar

I want to combine the contents of these two files, something (output) like this:

john smith
adam moore
max caviar

what i've already did:

first=()
getfirst() {
    i=0
    while read line # Read a line
    do
        array[i]=$line # Put it into the array
        i=$(($i + 1))
    done < $1
}
getfirst "/tmp/first.txt"
for a in "${array[@]}"
do
        echo "$a"
done

last=()
getlast() {
    i=0
    while read line # Read a line
    do
        array[i]=$line # Put it into the array
        i=$(($i + 1))
    done < $1
}
getlast "/tmp/first.txt"
for b in "${array[@]}"
do
        echo "$b"
done

I've done some look alike (using iteration):

for x in {1..2}
do
echo $a[$x] $b[$x];
done

but the output is only:

max caviar
1
  • You create the first and last arrays, but never use them. Then you access arrays a and b, but these weren't declared as arrays, they're just the iteration variables in the two for loops. Commented Dec 27, 2014 at 21:38

1 Answer 1

6

A simpler solution is using paste:

$ paste -d ' ' first.txt last.txt
john smith
adam moore
max caviar

If you don't have paste, then using arrays:

$ first=($(cat first.txt))
$ last=($(cat last.txt))
$ for ((i = 0; i < 3; ++i)); do echo ${first[$i]} ${last[$i]}; done
john smith
adam moore
max caviar
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.