Search code examples
linuxbashwhile-loopcut

How to cut the nth line of file by using the value of the nth line from another file?


i tried to cut the first line of file A with the value in the first line of file B, the 2nd line of file A with the value of in the 2nd line of file B and so on ...

I tried this code:

while IFS= read -r line; do
  cut -c $line- file.A
done < file.B >out.txt

the issue is, that bash cut all lines from file A with the value of the first line, followed by cutting all line from file A with the 2nd value of the file B...

Can someone help me?


Solution

  • You have to read both files line by line. This can be done with an additional file descriptor

    while IFS= read -r a && IFS= read -ru3 b; do
      cut -c "$a"- <<< "$b"
    done < file.A 3< file.B > out.txt
    

    Here you can also use bash built-ins instead of cut to make the script run a bit faster:

    while IFS= read -r a && IFS= read -ru3 b; do
      printf %s\\n "${b:a-1}"
    done < file.A 3< file.B > out.txt
    

    Both commands from above assume 1-base indices as the code in your question did too. If you are using 0-based indices, change the loop body to

    cut -c "$((a+1))"- <<< "$b"
    

    or

    printf %s\\n "${b:a}"