grep on a variable containing a string with a tab

2019-09-20 15:08发布

问题:

I have a for loop that loops over a few lines. each line has two strings with a tab separating them e.g

chr11   105804693

when I pass the variable to grep with a file to search in it returns "105804693: No such file or directory". my code looks like this:

for line in $(cat list_of_lines); do grep $line file_to_search_in >> output_file; done

I tried to printf the variable and it returned "chr11" but when I echoed the variable it returned "chr11 105804693"

How can I call grep on the variable and have it search for the full line?

回答1:

You probably haven't added quotes around your variable having the search pattern,

search_pattern_variable="chr11 105804693"
grep "$search_pattern_variable" input-file

Since your variable had the words chr11 105804693, shell split up the words into multiple words with the default IFS (field-separator) and had used chr11 as the pattern and 105804693 as the file-name, which it is reporting not seeing such a file.

See what Word-Splitting means in bash.



标签: bash grep