Re: AWK number range (425 Views)
Reply
Super Advisor
Patrick Ware_1
Posts: 216
Registered: ‎12-14-2004
Message 1 of 7 (425 Views)
Accepted Solution

AWK number range

Hello all. I am in the process of doing mass edits on a file that deals with security defaults. I am using an awk line to check for PASSLENGTH being 8 or more in the file. If it is less than 8, I want to replace the line with:

PASSLENGTH=8

Currently I am accomplishing this with the following below:

awk '{sub(/PASSLENGTH=6|PASSLENGTH=5|PASSLENGTH=4/,"PASSLENGTH=8")};{print}' ${CHG_FILE} > ${CHG_FILE}.tmp
mv ${CHG_FILE}.tmp ${CHG_FILE}

What I need to know is if there is a way to specify a range, or tell it instead that if the value for PASSLENGTH is 0=7, then take action?

Don't worry, when I pick up the kids today, I will be at the book store getting an awk reference book.
Acclaimed Contributor
Dennis Handly
Posts: 25,291
Registered: ‎03-06-2006
Message 2 of 7 (425 Views)

Re: AWK number range

Something like:
awk '
{
sub(/PASSLENGTH=[0-7][^0-9]/,"PASSLENGTH=8")
print}'

If it is a two digit number, it will fail if you have 07.
Super Advisor
Patrick Ware_1
Posts: 216
Registered: ‎12-14-2004
Message 3 of 7 (425 Views)

Re: AWK number range

0=7 should read as 0-7 in my first post.
Honored Contributor
Hein van den Heuvel
Posts: 6,588
Registered: ‎05-19-2003
Message 4 of 7 (425 Views)

Re: AWK number range

How firm/predictable is the input ?

Any optional spaces or line comments to deal with?

You could tell awk to
- first look for lines starting with PASSLENGTH
- split into an array of words around =
- compare the second word with 8
- force fresh $0 line if less than 8
- print $0

$ awk '/^PASSLENGTH=/{ split ($0,a,/=/); if (a[2] < 8) $0 = a[1] "=8"} {print}' tmp.txt

example input/output below.

Hein

$ cat tmp.txt
PASSLENGTH=12
PASSLENGTH=18
PASSLENGTH=06
PASSLENGTH=6
xxxxxENGTH=6
PASSLENGTH=08
PASSLENGTH=0
PASSLENGTH=2
PASSLENGTH=10

---- output ----

PASSLENGTH=12
PASSLENGTH=18
PASSLENGTH=8
PASSLENGTH=8
xxxxxENGTH=6
PASSLENGTH=08
PASSLENGTH=8
PASSLENGTH=8
PASSLENGTH=10

Super Advisor
Patrick Ware_1
Posts: 216
Registered: ‎12-14-2004
Message 5 of 7 (425 Views)

Re: AWK number range

Dennis, for some reason the help you gave me didn't seem to work out for me.
Acclaimed Contributor
Dennis Handly
Posts: 25,291
Registered: ‎03-06-2006
Message 6 of 7 (425 Views)

Re: AWK number range

>for some reason the help you gave me didn't seem to work out for me.

Possibly you only had one digit, this works a little better:
sub(/PASSLENGTH=[0-7]$/,"PASSLENGTH=8")

But as with Hein's example, it is better to get that number than try to pattern match the possibly two digits.
Super Advisor
Patrick Ware_1
Posts: 216
Registered: ‎12-14-2004
Message 7 of 7 (425 Views)

Re: AWK number range

Yes, it was only single digit numbers.
The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation.