shift-e
shift-e

Reputation: 13

Use awk to pattern matching

I have a file hoge.txt like this:

case $1 in
[ $input = "q" ] && exit
if [ -s $filename ]    
if [ ! -f $1 -o -f $2 ]
echo $list
rm -f ${BKDIR}
BKDIR=/${HOME}/backup

And I want to find all alphabetic variables, exclude every parameters like "$1" and output to a new file like this:

$input
$filename
$list

The best i can do now is

cat hoge.txt | awk '{for(i=1;i<=NF;i++){ if($i=="$/[a-zA-Z]/"){print $i} } }'

But it doesn't return any results.

Upvotes: 1

Views: 121

Answers (1)

Inian
Inian

Reputation: 85560

You don't need to use Awk for such a trivial example, just use extended regular expressions support using the -E flag and print only the matching word using -o

grep -Eo '\$[a-zA-Z]+' file

produces

$input
$filename
$list

and write to a new file using the re-direction(>) operator

grep -Eo '\$[a-zA-Z]+' file > variablesList

(or) saving two key strokes (suggested in comments below) with enabling the case insensitive flag with -i

grep -iEo '\$[a-z]+' file

Upvotes: 1

Related Questions