Shell script to rip form variable names to a file?

michaelsanford

Translator, Web Developer
I have a rather large for that I want to get the variable names from, so that I can quickly make a PHP page without having to recopy them all by hand.

I've gotten this far
cat ncf.html | grep -e '<input' | grep -e 'name='

But this just gives me the full lines of every instance of those variable names (i.e., each form element). I can't figure out how to make the script get the part after name= (so XXX, the variable name) and parse that into a file (with a simple redirection operator).

Any ideas?
 
You started with:

cat ncf.html | grep -e '<input' | grep -e 'name='

Let me start off by pointing out a few details about what you have here already.

Firstly, you don't need the cat; just supply the source filename as the final argument to the first grep.

Secondly, you generally don't need to use -e. The first non-option thing you supply to grep is assumed to be the match pattern.

Lastly, you could choose to do this with a single grep, looking for both of these strings on a single line, rather than with two. Using the -E option allows you to use full regular expressions, not just simple strings.

So with all that, what you have so far would have:

grep -E '\<input.*name\=' ncf.html


(Note that that doesn't actually get you anything that you didn't already have, but it's slightly better form, and it never seems to hurt to develop good habits about such things.)


Okay, so now on to actually answering your question.

The next tool you want is probably sed. sed's most common usage is to do substitutions on text that it's fed; it also can speak regular expressions, and can obviously substitute nothing for strings, thus deleting them. A simple example of a common way to use sed is:

sed 's/search/replace/'

So if you want to delete everything up through name=", and then delete everything from " onward, you could do something like:

grep -E '\<input.*name\=' ncf.html | sed 's/.*name\=\"//' | sed 's/\".*//'


Sorry for rambling on at such length, and hope this helps you out.
 
Back
Top