Tyler Shambora
Tyler Shambora

Reputation: 67

Appending Text From A File To Text In Another File

I have two separate text files, one with 4 letter words and one with 4 digit numbers, all on individual lines. The words in the on file correspond to the numbers on the same line in the other file. For example:

CATS
RATS
HATS

matches up with

2287
7287
4287

What I would like is to append the numbers to the end of their matching word, so it looks like this:

CATS2287
RATS7287
HATS4287

so far what I have is this:

for i in $(cat numbers); do  
  sed 's/$/'$i'/' words;
done

but the problem is a) that doesn't print/echo out to a new file and b) it loops through each word every time the first loop comes to a new number so in the end, all the words are paired up with the last number in the number file. Thanks in advance for the help.

Upvotes: 3

Views: 718

Answers (5)

turf
turf

Reputation: 11

On Mac OS X:

paste -d "\0" <(echo abc) <(echo def)

Upvotes: 1

kurumi
kurumi

Reputation: 25609

there are a few ways to do that

Paste:

paste -d "" file1 file2

awk

awk '{ getline f<"file2" ; print $0f}' file1

Bash:

exec 6<"file2"
while read -r line
do
    read -r S <&6
    printf "${line}${S}\n"
done <"file1"
exec >&6-

Ruby(1.9+)

ruby -ne 'BEGIN{f=File.open("file1")};print $_.chomp+f.readline;END{f.close}' file

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 247210

Hmm, my version of paste with -d"" just results in numbers, the words get overwritten (GNU paste 8.10 on cygwin). my input files have no carriage returns.

paste words numbers | tr -d '\t'

Also, just with shell builtins

exec 3<words
exec 4<numbers
while read -u3 word; do
  read -u4 num
  echo $word$num
done
exec 3<&-
exec 4<&-

Upvotes: 1

sarnold
sarnold

Reputation: 104110

You can use the excellent little paste(1) utility:

$ cat a
CATS
RATS
HATS
$ cat b
2287
7287
4287
$ paste -d "" a b
CATS2287
RATS7287
HATS4287
$ 

-d specifies a list of delimiters; I gave it a blank list: no delimiters, no delimiters.

Upvotes: 2

SiegeX
SiegeX

Reputation: 140537

paste -d "" /path/to/letters /path/to/numbers

Proof of Concept

$ paste -d "" CATS NUMS
CATS2287
RATS7287
HATS4287

Upvotes: 2

Related Questions