0
votes

I am not sure what I am doing wrong in following situation - I want to merge multiple files into one, but I want to merge a lot of them, so I want to use something like this:

*input file* that contains lines 
file1.txt >> mergedfiles1.txt 
file2.txt >> mergedfiles1.txt 
file3.txt >> mergedfiles2.txt
file4.txt >> mergedfiles2.txt
...

If I try to use simple script as I usually do

cat *input file* | while read i
do
cat $i
done

it actually doesn't merge the files, but writes

*content* of file1.txt
cat: >> : file does not exist
cat: mergedfiles1.txt : file does not exist

I have tried to put command cat right at the beginning of each line of the input file but it did not work as well.

I guess it is a simple mistake, but I am not able to find a solution.

Thanks for help.

4

4 Answers

1
votes

You can merge your three files using cat this way:

cat file1 file2 filet3 > merged_files
0
votes

you need to use it like this

cat input_file > output file
0
votes

That's because bash treats an empty space as a line separator.

So you've got to manage this thing.

Actually, you can remove the >> from your input file and do something like this :

k=0
for line in $(cat inputFile); do
    if [ $k -eq 0 ]; then
        src=$line
    let k=$k+1
    else
    cat $src>>$line
    k=0
    fi
done

It's been a while since my last bash script, but the logic is pretty simple.

Since bash uses the spaces a line separators, you have to keep a counter to know if the line's really over. So we're using k. Having k = 0 means that we're in the first half of the line, so we need to store the filename into a var (src).

When k is 1, it means that we're in the final half of our line, so we can actually execute the cat command.

My code will work if your text is like :

file1.txt mergedfiles1.txt
file2.txt mergedfiles1.txt
file3.txt mergedfiles2.txt
file4.txt mergedfiles2.txt
0
votes

I wasn't quite sure what you wanted to do, but thought this example might help:

#!/bin/bash

SAVEIFS=$IFS
IFS=$(echo -en "\n\b")

for file in *
do
    echo "$file"
done

IFS=$SAVEIFS

The manipulating of IFS is so you can pick up and process space separated files, which are more common coming out of Windows reports than -- at least from my experience -- Linux (Unix).