0

I have n number of files, I have stored filenames in a list and I want to combine them. I am doing this manually, i.e. If n=3

cat ${filename[1]} ${filename[2]} ${filename[3]} > newfile

If the content of the file is as follows:

filename[1]:
  line1
  line2

filename[2]:
  line3
  line4

filename[3]:
  line5
  line6

I want the newfile to have

newfile:
line1
line2
line3
line4
line5
line6

How can I do this automatically, i.e. for any number of files "n", I want to combine them sequentially as I am doing here for three files manually

1
  • The files have the same prefix? Are they sequential? Do they follow a specific sequence?
    – dryleaf
    Aug 24, 2015 at 23:52

3 Answers 3

4

You can use '@', for example:

$ files=( /tmp/a "/tmp/a file from windows" /tmp/myfile )
$ cat "${files[@]}" > newfile

The '@' expands the entire contents of the array. It is similar to *except it will treat each element individuals whereas * will combine all elements as one.

1
  • This works, thanks!. what does the @ command do? it combines calls all the elements of the list sequentially?
    – Syed Moez
    Aug 25, 2015 at 0:16
1

The easiest way to do this is:

$ for i in {1..3}; do cat inputfile$i>>outputfile; done
0

This is trivial with zsh.

% echo blah > a; echo asdf > b; echo harfjr > c;
% filenames=(a b c d e)
% print -l $filenames[1,3]
a
b
c
% cat $filenames[1,3]
blah
asdf
harfjr
% cat $filenames[1,3] > anewfile
% cat anewfile
blah
asdf
harfjr
% somenum=2   
% print -l $filenames[1,$somenum]
a
b
% 

If the shell is actually bash or ksh uhhh dunno.

5
  • would this combine the files?
    – Syed Moez
    Aug 24, 2015 at 23:55
  • I want to combine the context of the file. e.g. file1.txt has line1 line2 file2.txt has line3 line4 I want to combine them into a new file that has line1 line2 line3 line4
    – Syed Moez
    Aug 24, 2015 at 23:56
  • So pass the filenames to cat instead of print -l.
    – thrig
    Aug 24, 2015 at 23:58
  • thats what I am currently doing. Is there a way to automate this. Please see the edit in the question, may be that would make it clear
    – Syed Moez
    Aug 25, 2015 at 0:00
  • This is not working for me. I have file names as variables in a list, the above code gives me error. I am accessing them as ${filenames[1,3]} but doing this only copies the content of 2nd file into the new file
    – Syed Moez
    Aug 25, 2015 at 0:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .