0

I'm sorry for my poor English, first. I want to read a file (tel.txt) that contains many tel numbers (a number per line) and use that line to grep command to search about the specific number in the source file (another file)!

I wrote this code :

dir="/home/mujan/Desktop/data/ADSL_CDR_Text_Parts_A"
file="$dir/tel.txt"
datafile="$dir/ADSL_CDR_Like_Tct4_From_960501_to_97501_Part0.txt"

while IFS= read -r line
do
    current="$line"
    echo `grep -F $current "$datafile" >> output.txt`
done < $file

the tel file sample :

44001547
44001478
55421487

but that code returns nothing! when I declare 'current' variable with literals it works correctly! what happened?!

Paul Hodges
  • 13,382
  • 1
  • 17
  • 36
Mujan
  • 316
  • 1
  • 13

3 Answers3

6

Your grep command is redirected to write its output to a file, so you don't see it on the terminal.

Anyway, you should probably be using the much simpler and faster

grep -Ff "$file" "$datafile"

Add | tee -a output.txt if you want to save the output to a file and see it at the same time.

echo `command` is a buggy and inefficient way to write command. (echo "`command`" would merely be inefficient.) There is no reason to capture standard output into a string just so that you can echo that string to standard output.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • 1
    Might also want to use grep's `-x` option (if it's available) to make these "full-line" expressions. – ghoti Feb 13 '19 at 13:22
  • @ghoti Good addition, though it's not clear from the question whether the OP simply forgot to mention this, or if they need something else. – tripleee Feb 13 '19 at 13:23
0

Why don't you search for the line var directly? I've done some tests, this script works on my linux (CentOS 7.x) with bash shell:

#!/bin/bash
file="/home/mujan/Desktop/data/ADSL_CDR_Text_Parts_A/tel.txt"

while IFS= read -r line
do
    echo `grep "$line" /home/mujan/Desktop/data/ADSL_CDR_Text_Parts_A/ADSL_CDR_Like_Tct4_From_960501_to_97501_Part0.tx >> output.txt`
done < $file

Give it a try... It shows nothing on the screen since you're redirecting the output to the file output.txt so the matching results are saved there.

Bogdan Stoica
  • 4,349
  • 2
  • 23
  • 38
  • This preserves many of the antipatterns and inefficiencies in the original code. The [useless use of `echo`](http://www.iki.fi/era/unix/award.html#ercho) is particularly sad. – tripleee Feb 13 '19 at 13:11
  • I know, thank you for pointing it out. I was trying to keep the script in the initial form... But I'll agree, your approach is better – Bogdan Stoica Feb 13 '19 at 13:13
0

You should use file descriptors when reading with while loop.instead use for loop to avoid false re-directions

dir="/home/mujan/Desktop/data/ADSL_CDR_Text_Parts_A"
file="$dir/tel.txt"
datafile="$dir/ADSL_CDR_Like_Tct4_From_960501_to_97501_Part0.txt"

for line in `cat $file`
do
    current="$line"
    echo `grep -F $current "$datafile" >> output.txt`
done
Akhil
  • 912
  • 12
  • 23