Parse a string, assign to script variable

November 16, 2010 at 13:52:14
Specs: Windows XP

Script is called with filename as variable.
Incoming file name is 'epaid_111510_048.txt' for Nov. 15, 2010
Need to parse out year, assign to script variab;e
So can use variable to build name of directory to put file in.

echo $1 | awk '{ print substr($0, length($0) - 9, 2) }' returns 10 in output - this is correct, but useless

fileyear = $(echo $1 | awk '{ print substr($0, length($0) - 9, 2) }' ) returns "Variable syntax" error

Can't seem to get the result into a script var.

A little help here, plz


See More: Parse a string, assign to script variable

Report •


#1
November 16, 2010 at 13:59:51

could you do something like:

VARIABLE='{ print substr($0, length($0) - 9, 2) }'

and then call VARIABLE


Report •

#2
November 16, 2010 at 15:18:52

Nope. substr() is an awk function. So have to call awk to use it.

Report •

#3
November 16, 2010 at 15:22:23

but you basically want to load that 10 output into a variable right?

what about this

VARIABLE=awk '{ print substr($0, length($0) - 9, 2) }


Report •

Related Solutions

#4
November 16, 2010 at 15:33:53

Nope. Like I said at the start, it returns "Variable syntax", whatever that means.
This is hp-ux, if that means anything.
Maybe this just can't be done in unix.

Looks like I'll have to tray the long way round. I can pipe this to a file.
So then I find the file, open the file, read the first line of the file into a variable.
Now I just have to figure that out.


Report •

#5
November 16, 2010 at 17:37:42

Your problem probably is that you have spaces before and after the = sign:

fileyear=$(echo "$1" | awk '{ print substr($0, length($0) - 9, 2) }' )

Also, the double quotes around $1 are optional, but are required if $1 contains spaces.


Report •

#6
November 16, 2010 at 18:12:29

No cigar.
Honestly, I've spent most of my day poring over websites, tearing up my UnixInANutshell, and am tired of the incredibly cryptic "Variable syntax" as an error message from this version of unix.

Off on a vacation. Not just because of this...but this added to the need...


Report •

#7
November 16, 2010 at 22:13:57

What shell are you using? ksh, bash?

Because this command substituion example will not work with the bourne shell:

fileyear=$(echo "$1" | awk '{ print substr($0, length($0) - 9, 2) }' )

Use the back tic for bourne:

fileyear=`echo "$1" | awk '{ print substr($0, length($0) - 9, 2) }' `


Report •


Ask Question