Reputation: 341
I have a file named email.txt like these one :
Subject:My test
From:my email <[email protected]>
this is third test
I want to take out only the email address in this file by using bash script.So i put this script in my bash script named myscript:
#!/bin/bash
file=$(myscript)
var1=$(awk 'NR==2' $file)
var2=$("$var1" | (grep -Eio '\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b'))
echo $var2
But I failed to run this script.When I run this command manually in bash i can obtain the email address:
echo $var1 | grep -Eio '\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b'
I need to put the email address to store in a variable so i can use it in other function.Can someone show me how to solve this problem? Thanks.
Upvotes: 19
Views: 99818
Reputation: 243
There's a cruder way:
cat $file | grep @ | tr '<>' '\012\012' | grep @
That is, extract the line(s) with @ signs, turn the angle brackets into newlines, then grep again for anything left with an @ sign.
Refine as needed...
Upvotes: 0
Reputation: 7589
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.
Upvotes: 28
Reputation: 676
There are very helpful flags for bash: -xv
The line with
var2=$("$var1" | (grep...
should be
var2=$(echo "$var1" | (grep...
Also my version of grep doesn't have -o flag.
And, as far as grep patterns are "greedy" even as the following code runs, it's output is not exactly what you want.
#!/bin/bash -xv
file=test.txt
var1=$(awk 'NR==2' $file)
var2=$(echo "$var1" | (grep -Ei '\b[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}\b'))
echo $var2
Upvotes: 1
Reputation: 891
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')
Upvotes: 11