passing grep into a variable in bash

What is happening is this:

var2=$("$var1" | (grep -Eio '\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b'))
       ^^^^^^^ Execute the program named (what is in variable var1).

You need to do something like this:

var2=$(echo "$var1" | grep -Eio '\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b')

or even

var2=$(awk 'NR==2' $file | grep -Eio '\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b')

I think this is an overly complicated way to go about things, but if you just want to get your script to work, try this:

#!/bin/bash

file="email.txt"

var1=$(awk 'NR==2' $file)

var2=$(echo "$var1" | grep -Eio '\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b')

echo $var2

I'm not sure what file=$(myscript) was supposed to do, but on the next line you want a file name as argument to awk, so you should just assign email.txt as a string value to file, not execute a command called myscript. $var1 isn't a command (it's just a line from your text file), so you have to echo it to give grep anything useful to work with. The additional parentheses around grep are redundant.

Tags:

Linux

Bash

Grep