2

i is an integer (lets say 4). I have three text files (a,b,c) contain single lines with strings, total number of lines of files equal to i (4). For example "a" file contains;

trm320
abc000
dfg1002
der5205

I need to create the output (on the screen or in the text file) with loop like;

a(1) b(1) c(1) (first line of a,b,c files)


a(4) b(4) c(4) (last line of a,b,c files)

What kind of loop do I need to create?

1 Answer 1

3

paste does exactly what you want.

DESCRIPTION
       Write  lines  consisting  of  the sequentially corresponding lines from
       each FILE, separated by TABs, to standard output.   With  no  FILE,  or
       when FILE is -, read standard input.

       Mandatory  arguments  to  long  options are mandatory for short options
       too.

       -d, --delimiters=LIST
              reuse characters from LIST instead of TABs

In your case

paste -d " " a b c

will do the trick. If you need the output in a file, redirect >output the output.


To access the n-th line of a file, use sed. For convenience wrap it up in a Bash function (pl is supposed to mean Print Line)

function pl {
  sed -n "$1p" $2
}

Calling for example pl 5 a will print the fifth line of file a. To store it in a variable

fifth=$(pl 5 a)

or combine both tasks

paste a b c | pl 5 -

to print the fifth line of the concatenated file.


To get a file into an array, use mapfile, from this answer:

mapfile -t myArray < output.txt
7
  • +1 much better than any written bash script. Useful utility!
    – Tim
    Oct 20, 2015 at 11:07
  • I also need to define variable. For example when I type $a[1] I want to see first line. Is there any way to define these variables like that? Oct 20, 2015 at 11:07
  • @Tim Why invent the wheel anew every time, right?. The GNU toolbox holds a plethora of those useful helpers.
    – Nephente
    Oct 20, 2015 at 11:08
  • for example; sentence="this is a story" stringarray=($sentence) echo ${stringarray[0]}; I need to define the lines of text files with this way Oct 20, 2015 at 11:12
  • @deepblue_86 it's helpful to tell us that at the beginning. You could then cat them and add each line of file to an array
    – Tim
    Oct 20, 2015 at 11:21

You must log in to answer this question.

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