0

When I try to extract rows that are matched string which are in another file.But the grep command returns nothing.

#!/bin/bash
input="export.txt"
file="filename.csv"
val=`head -n 1 $file`
echo $val>export.csv
cat export.txt | while read line 
do
   val=`echo $line | tr -d '\n'`
echo $val
valu=`grep $val $file`
 echo $valu
done


halfer
  • 19,824
  • 17
  • 99
  • 186
krishna
  • 147
  • 1
  • 2
  • 9
  • 1
    Please don't use backticks \`, they are discouraged. Use `$(...)` instead. [Obsolete and deprecated syntax in bash](https://wiki-dev.bash-hackers.org/scripting/obsolete). So just do `grep -f export.txt filename.csv`? – KamilCuk Nov 26 '19 at 13:08
  • I used $(...).But this also not helped me – krishna Nov 26 '19 at 13:11
  • 1
    There are many issues with the current approach. Too many to list here, as @KamilCuk says, use `grep -f export.txt filename.csv` – Fredrik Pihl Nov 26 '19 at 13:16
  • @FredrikPihl.I used that command also that also not helped – krishna Nov 26 '19 at 13:22
  • 1
    Then show us the content of your files and the expected output. Just a few lines are enough. Update your question with this information and we'll take look. e.g. see [this](https://pastebin.com/VaTkDwgX) – Fredrik Pihl Nov 26 '19 at 13:23
  • I added a duplicate, but I removed it again. Two things that are going to bite you for sure: you're modifying variables in a while loop (see [here](https://stackoverflow.com/questions/16854280/a-variable-modified-inside-a-while-loop-is-not-remembered)), and all the unquoted expansions like `grep $val $file` will bite you when `$val` contains blanks. – Benjamin W. Nov 26 '19 at 14:30
  • 1
    your data may need cleaning up. try `dos2unix $file ; dos2unix export.txt` and see if that helps. Good luck. – shellter Nov 26 '19 at 14:33

1 Answers1

0

You can simply do this :

grep -f list.txt input.txt

Which will extract all the lines from input which match any word from list.txt.

If for some reason you want to save each match, you can do it in a Bash array as :

IFS=$'\n' read -d '' -a values <<< "$( grep -f list.txt input.txt )"

And then you can print a certain match as :

echo "${values[1]}"

Regards!

Matias Barrios
  • 4,674
  • 3
  • 22
  • 49