0

I have a shell script; say test.sh with the following contents:

for j in *_seqs.txt; do  

    while read line; do

    count_of_occurences=$(grep "^$line" $j)
    echo $count_of_occurences
    done < $1

done

and a couple of files in the same folder; say

1_seqs.txt
2_seqs.txt
3_seqs.txt
4_seqs.txt
5_seqs.txt

The contents of say 1_seqs.txt may look like

AAA0030309
3300AAA009
00AAA33030
AAA0022033

I have another file, say alphabets.txt with following contents

AAA
BBB
CCC

I want to look the contents of alphabets.txt in all the *_seqs.txt using the shell script test.sh. And I want to find if say AAA appears in the beginning of a line of say 1_seqs.txt and so on.

I am unable to do so when I run the script like this

sh test.sh alphabets.txt

For some reason, grep is unable to look at the beginning when the string is stored in the variable $line within test.sh.

My output of the script should be

AAA0030309
AAA0022033
  • 1
    What happens instead? One thing you're missing is quoting of your variables (so for example $count_of_occurences will undergo word splitting). FWIW you might want to look at alternatives like sed 's/^/^/' alphabets.txt | grep -f- *_seqs.txt – steeldriver May 5 at 13:39
  • Your expected output is at odds with your shell script. In the script you are outputting the number of times the patterns can be found, but you expect the output the contents of the lines that matches? Could you clarify, and also show what actually happens, as steeldriver requested? Please edit the question rather than replying in comments. – Kusalananda May 5 at 14:37
0

Your script almost already does what you want. You don't need the grep capture which just complicates the printing:

#!/bin/bash

for j in *_seqs.txt; do  
  while read line; do
      grep "^$line" "$j"
  done < "$1"
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.