Appending string on every line and make new file

57 Views Asked by At

I need some direction on a bash that will take a list of words and append each word with words from another list:

List 1

1
2
3

List 2

!
@
#

New Lists (A)

1!
2!
3!

(B)

1@
2@
3@

(C)

3!
3@
3#

How I started it:(I Suppose I should note I gave up having two input files to I went with a counter function instead.)

#!/bash/bin
CT=1000 
LIMIT=10000 
while [ "$CT" -lt "$LIMIT" ] 
do 
    echo $CT 
    sed -e 's/$/'$CT'/' -i 'INPUTFILE.txt' 
let "CT +=1" 
done
1

There are 1 best solutions below

1
On BEST ANSWER

Assuming you want numbered output files, try running a counter inside the loop.

#!/bin/bash
i=0
while read -r suffix; do
   let i++
   sed "s/$/$suffix/" INPUTFILE.txt >file$i
done <SUFFIXFILE.txt

Note that sed -i will manipulate the original input file in-place. You don't want that; you want the output in a new file. So we remove the -i option and use the shell's redirection feature to indicate where to send standard output.

If you want to enumerate the destination file names, that's a bit trickier. One solution is to add the destination file name to the suffix file

!        A
@        B
#        C

then read both tokens in the loop:

while read -r suffix outputfile; do
    sed "s/$/$suffix/" INPUTFILE.txt >"$outputfile"
done <SUFFIXLIST.txt

or if you want to embed this information in your script, use a here document:

while read -r suffix outputfile; do
    sed "s/$/$suffix/" INPUTFILE.txt >"$outputfile"
done <<____HERE
    !        A
    @        B
    #        C
____HERE

(The only Bash-specific construct is let for arithmetic, so the latter two scripts which don't use that can be run with /bin/sh instead of Bash.)