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.
Grep works well with standard input. This allows us to use grep to match a pattern from a variable. It's is not the most graceful solution, but it works. To learn more about standard streams (STDIN, STDOUT, & STDERR) and Pipelines, read "Linux I/O, Standard Streams and Redirection".
You can use: targets=($(grep -HRl "pattern" .)) Note use of (...) for array creation in BASH. Also you can use grep -l to get only file names in grep 's output (as shown in my command).
We can use grep -q in combination with an if statement in order to test for the presence of a given string within a text file: $ if grep --binary-files=text -qi "insert" test_data. sql; then echo "Found!"; else echo "Not Found!"; fi Found!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With