Search code examples
bashtail

Utilising variables in tail command


I am trying to export characters from a reference file in which their byte position is known. To do this, I have a long list of numbers stored as a variable which have been used as the input to a tail command.

For example, the reference file looks like:

ggaaatgcattcaaacatgc

And the list looks like:

5
10
7
15

I have tried using this code:

list=$(<pos.txt)
echo "$list"
cat ref.txt | tail -c +"list" | head -c1 > out.txt

However, it keeps returning "invalid number of bytes: '+5\n10\n7\n15...'"

My expected output would be

a
t
g
a
... 

Can anybody tell me what I'm doing wrong? Thanks!


Solution

  • It looks like you are trying to access your list variable in your tail command. You can access it like this: $list rather than just using quotes around it.

    Your logic is flawed even after fixing the variable access. The list variable includes all lines of your list.txt file. Including the newline character \n which is invisible in many UIs and programs, but it is of course visible when you are manually reading single bytes. You need to feed the lines one by one to make it work properly.

    Also unless those numbers are indexes from the end, you need to feed them to head instead of tail.

    If I understood what you are attempting to do correctly, this should work:

    while read line
    do
      head -c $line ref.txt | tail -c 1 >> out.txt
    done < pos.txt