Showing posts with label awk. Show all posts
Showing posts with label awk. Show all posts

Friday, November 21, 2008

Another Simple Scriptlet To Make The Unix And Linux CLI More User Friendly

Hey there,

Today we're going to shoot out another quick scriptlet that might be useful (or distracting ;) from time to time. It’s a bit of a follow up on our post from earlier this week on using bash to produce fancy user names for folks logged into your machine, although it’s a little bit longer. Once again, if you go by the 65 character rule, this isn’t a one liner, even though it’s all going on one line ;)

Our little foray into variable interpolation today has to do with making /etc/passwd just a bit more accessible. Most folks are familiar with the 7 colon-separated fields of this file (if not, they’re: The user’s Username, an encrypted password (or usually an “x” if you’re using a shadow password system), the user’s UID, the user’s GID, the user’s gecos information (Also referred to as the “comment field,” usually either empty or populated with a short description to make the account more easily recognizable) , the user’s home directory and, finally, the user’s default shell)

Now, say what you will about the structure and setup of the passwd file, but it’s fairly easy to follow. Almost everything in it is the opposite of cryptic. The password field (field number 2) is, of course, not going to be tailored for your ease of understanding ;) If you get really lucky and you hop on a machine that actually lists the encrypted password in field two of /etc/passwd, you can copy the file to any remote machine and go to work on it. We've posted quite a few scripts to do automated password cracking. You should just see an "x" for a standard user account. If you don’t, have a talk with your SysAdmin or, if you’re him, please move on to a shadowed password system. Too much information exists in the public domain to make the old-style setup anything more than a trifling hassle to someone who wants to exploit your system. Especially a disgruntled employee!

Other than that, the user ID (field number 3) is an easy relation to make, since the username is in the same file (field number 1). The only thing in there that doesn’t practically explain itself is field number 4; the GID (group id) field. It’s not that big of a deal to look a user up in /etc/passwd, glean that group id information and find out what group the user is in by looking at /etc/group. It’s as simple as this:

host # grep user1 /etc/passwd
user1:x:37527:501::/export/home/user1:/bin/bash
host # grep 501 /etc/group
people::501:


and, just like that, we know that the user "user1"'s primary group membership is in the group "people." There are also secondary groups to consider, but finding this out is trivial as well. Just do the following:

host # grep -w user1 /etc/group
guys::600:user1
folks::601:user1


And, yes, I can hear you out there ;) I'm aware of commands like "groups" and "id" ;) They're very good at getting this information, as well (which is why we're going to use "groups" in our one-long-liner. Your output may look slightly different). Note that some versions don't have the -a option for "id" and some have either -g, -G, any combination of the three or all of them - it depends on your distro:

host # groups <-- This is supposed to list groups in order, from left to right, with the leftmost group being the "primary" and every group after that being a "secondary." The ordering of the "secondary" groups in the list is generally "as they appear" in /etc/group. So, since the line with "guys" is on a line closer to the beginning of the /etc/group file than the line with "folks," they're printed in that order. No other relationship exists between them that I'm aware of.
people guys folks
host # id -a
uid=37527(user1) gid=501(people) groups=501(people)
<-- On Solaris; not quite as helpful as "id" on other flavours of Linux or Unix.

Anyway, I think I've met my word-count quota ;) Just kidding. I have no idea how much I've typed. I'm not even sure I want to know...

Here's a nice little command line (and, consequently, the topic of this post ;) to print every user's group(s) in the (modified) output of /etc/passwd. Just type it out, like so:

host # IFSBAK=$IFS;export IFS=":";while read one two three four five;do groupnames=`groups $one|sed 's/ /,/g'`;echo "${one}:${two}:${three}:${groupnames}:${five}";done </etc/passwd;export IFS=$IFSBAK


...lots of output left out for reasons of brevity and security :) ...
noaccess:x:60002:noaccess:No Access User:/
user1:x:37527:people,guys,folks::/export/home/user1:/bin/bash
...


And, there we have it. All nice and tidy :) Here's the same thing in script format (below) to make it a little easier to read. Be sure (now matter how you run it) that you don't clip the beginning and end, as you'll probably want to reset your shell's IFS (field separator) to what it was before we changed it to the colon (:) to make parsing /etc/password possible without using awk or cut, etc... Also, if it's of any interest and you noted that I only counted my variables up to "five" it's because "while read" will swallow up the rest of a line in its last variable. So, instead of reading and writing five, six and seven, I just read five, since that would include from field five all the way to the end of the line (at the end of field 7), and field 4 (the group field) was the last field on every line that we were actually interested in :)

#!/bin/bash

IFSBAK=$IFS
export IFS=":"

while read one two three four five
do
groupnames=`groups $one|sed 's/ /,/g'`
echo "${one}:${two}:${three}:${groupnames}:${five}"
done </etc/passwd

export IFS=$IFSBAK


Have a great weekend!

, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Thursday, November 20, 2008

Plain English Explanation Of An Awk Statement For Linux Or Unix

Hey There,

Today's post is going to be a follow-up to yesterday's post on convoluted column arithmetic in awk. I have a nasty habit of listing all my stuff as "beginner" material. Mostly this is because I try to write my material for the middle level to newer user of Unix, Linux, Perl, etc. I have absolutely no interest in picking apart the finer points of quantum mathematics or advanced concepts in programming or operating system design and implementation. I leave that for the academics. Besides, if I did go that route, I'd have to narrow the scope of this blog a "whole lot" ;)

Yesterday's post offered a number of cut-and-paste awk solutions to solving some seemingly difficult data massaging problems and, in my frantic struggle to keep my post under a thousand words, I cut some corners and simply framed the problem, following it with the solution. It's usually a good formula. I'll be the first to admit, though, that the examples were somewhat of a test for me when I first slapped them together and probably deserved to be explained more than they were. To that end, we'll look at one of the examples from yesterday and pick it apart, so that the pieces all make sense to, hopefully, any and every one. I aim to please :)

The example we'll work with is from part one of problem 2, where we looked to add the even columns and, separately, the odd columns and then print those totals at the end of each line. The original awk statement and resultant solution follow (check yesterday's awk post for the original dataset. It doesn't really make a difference insofar as this explanation will be concerned):

host # awk '{sum1=$1;sum2=$2;for (i=3;i<=NF;i++) {if ( i%2 ) {sum1 += $i; printf"%.2f ", $i}else {sum2 += $i; printf"%.2f ", $i}}printf"ODDS %.2f EVENS %.2f\n", sum1, sum2}' DATASET2

51.61 48.39 41.38 58.62 32.00 68.00 56.41 43.59 57.52 42.48 ODDS 284.75 EVENS 315.25
49.06 50.94 42.86 57.14 100.00 0.00 0.00 100.00 11.49 88.51 ODDS 259.96 EVENS 340.04
52.17 47.83 26.83 73.17 61.54 38.46 57.69 42.31 33.33 66.67 ODDS 273.23 EVENS 326.77
34.38 65.62 0.00 100.00 59.26 40.74 100.00 0.00 43.43 56.57 ODDS 257.07 EVENS 342.93
25.53 74.47 35.56 64.44 84.42 15.58 47.53 52.47 0.00 100.00 ODDS 243.04 EVENS 356.96


At first glance, I suppose that awk statement could look imposing. Fortunately, once you pull it apart, it's not all that bad. First, we'll write the awk in "plain English." Here's what the linear thought process would be if we just spelled it out:

To start out, we'll set the variable sum1 to the value of the first field. Then, we'll set the value of the variable sum2 to the value of the second field (This sets us up with sum1 holding the first "odd" field value and sum2 holding the first "even" field value). After this we'll iterate through a looping construct that begins by setting the value of the variable i to 3, continues until the value of the variable i is less than or equal to the number of fields on any given line (NF), and increments the value of i by 1 after every pass.

For each invocation of the loop (which goes until the value of i becomes less than or equal to the number of fields on the line, or record), we check the value of the modulo of i and 2. If you want to look up the definitions of modulo and modulus, I strongly encourage it, but only if you're really curious ;) For our purposes, it will serve to explain that i%2 (i modulo 2) acts as a check on the remainder of a division operation. So, if the value of i is 3, i%2 is equivalent to 3 divided by 2. Since 3 doesn't divide evenly by 2, it leaves a remainder of 1. That remainder is the value of the equation i%2. On the next pass (and every pass where an even number is concerned) the value of i%2 will be 0 since, for instance, 4 divides evenly by two, with a remainder of 0. Hopefully this isn't becoming more confusing than it started out being ;)

So, knowing what we now know, the "if statement" that gets run in every iteration of the outer "for loop" does a little bit of "backward figuring" (that is to say that the logic may not seem to be correct at first glance, although it is ;) The "if conditional" tests the value of i%2. For all even numbers this is equal to 0 and for all odd numbers it is equal to 1. So the statement "if ( i%2 )" is testing the value of that statement. In the case of awk, and most shell equations and their return codes, 1 equals true and 0 equals false. It's almost like saying: If "true" (the case for all odd numbers) do this and if "false" (the case for all even numbers), do the other thing... On to the next part... I never thought this would be so hard to explain ;)

This next part is pretty simple. For the odd numbers, the value of the variable sum1 is made equal to its old value plus the value of the field we're reading on this pass. If the value of i is 3, then we're checking field 3 (or $3, if you prefer). For the even numbers, the value of the variable sum2 is made equal to its old value plus the value of the field we're reading; same as with the odds. If i equals 4, we're adding the value of the i field (field 4, or $4) to the already existing value of sum2. For both instances, we're doing a simple printf to output that value to the terminal.

Now, to end it all, when the value of the variable i becomes less than or equal to the number of fields (NF) on the line (or record), we slip in a quick printf statement to print the values of the odd numbers (sum1) and even numbers (sum2) before moving on to the next line. This can be a confusing point because, as you may know, awk (like sed, etc) operates on every line of a file when you feed it one. It's for this reason that we're so careful with the bracketing. If we weren't able to control where the totals printed out, they'd print only after all the lines in the input file were processed, which isn't what we wanted.

Finally, here's the exact same equation, broken up across several lines (I "chose" to do everything on one line for yesterday's examples, because that makes it easy for me to re-run statements using my line editor in bash :) Hopefully, looking at it in this way (in a proper script-like format) will help shed some more light on the "structure" of the process, just like the previous paragraphs, hopefully, helped elucidate some of the finer points of the "execution" of the process:

awk '{sum1=$1;sum2=$2
for (i=3;i<=NF;i++) {
if ( i%2 ) {
sum1 += $i; printf"%.2f ", $i
}else {
sum2 += $i; printf"%.2f ", $i
}
}
printf"ODDS %.2f EVENS %.2f\n", sum1, sum2
}' DATASET2


if you slapped the above in a file, called it "awky.sh" and ran:

host # sh awky.awk

you'd get the exact same results as you got from the one-line version above.

Hopefully, this explanation has been helpful and, if not, please let me know what still remains a point of confusion for you. Unless there are a lot of requests for certain specific bits of info that would warrant another post, I'll be happy to help clear up little bits and pieces either via email or on the boards :)

Cheers,

, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.



, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Wednesday, November 19, 2008

Convoluted Column Arithmetic Examples Using Awk On Linux Or Unix

Hey There,

Today's going to be a "fun with awk" day. I figure we should have one now because we never had them in school when I was a kid... The topic, as the title suggests, has to do with columnar arithmetic or, less pompously put, performing arithmetic operations on columns or, even more accessibly, adding stuff up ;) It's somewhat like our older post on doing simple cumulative math with awk, but slightly more confusing.

The basic premise here is that you, I and the next guy have all seen the solution to many a question like: "Given a file filled with rows of space delimited numbers, how do I add up all the values for field 2 ($2) in awk so that I can get the total when awk is through processing my file?" ...or something to that effect. Knowing the fundamentals of performing arithmetic in awk can be a great asset to you at work (or, at play, if you like to add, subtract, multiply and divide for kicks ;), but, for the most part, only the most banal instances of its application are either used or queried for on the web (at least as far as my search engine testing has shown so far).

So, without further fanfare, we'll take a look at two sets of data (below) and some various (hopefully, not utterly pedestrian) ways to sort and manipulate the data. These are pulled from a series of posts I answered on the Daniweb.com Shell Scripting Forum regarding odd and even column operations (I try to only plagiarize myself ;). I found the questions interesting to answer and, hopefully, you'll find both the requests and their resolutions of some use, as well :) I've modified some of the solutions that I posted to the board for this blog post, as I found that, at some points, my quick (trying to be helpful) answers could be done a bit better with a little extra attention. Also, the entire thread isn't played out here and some additional problems haven't been included. There's only so much I can type ;)

The setup involves a file that contains these numbers in the columns and rows - or fields and records, as we'll refer to them from here on out - shown below. The initial problem uses this dataset. The result of the initial solution forms the dataset for all the problems to follow (shown below, in, hopefully, sensible order):

Data Set 1:

55 65 48 45 48 68 32 68 44 34 88 65
82 63 52 54 51 68 75 0 0 20 10 77
55 77 60 55 22 60 40 25 75 55 45 90
20 80 33 63 0 64 32 22 75 0 43 56
54 54 12 35 48 87 65 12 77 85 0 15


Problem 1: Given "Data Set 1" (conveniently placed in a file called "DATASET1"), for each pair of successive fields , using awk's built in arithmetic operators, convert each field by dividing it by the sum of the pair and multiplying each by 100 to produce recognizable relative-percentage output. So, for the first column, you would have the results of equations of the following order:

$1/$1+$2, $2/$1+$2, $3/$3+$4, $4/$3+$4, etc....

Solution 1: This can be worked out by the following awk command (technically not a "one-liner" since it exceeds the 65 character limit):

host # awk 'BEGIN{lasti=1}{for (i=1;i<=NF;i++) {if ( i%2==0 ) {y=$lasti+$i;printf("%.2f %.2f ", $lasti/y*100, $i/y*100)}lasti=i }printf"\n" }' DATASET1

This solution produces the following output, which will become "Data Set 2" (which will be put in a file called.... DATASET2. I couldn't come up with anything more clever under pressure ;)

45.83 54.17 51.61 48.39 41.38 58.62 32.00 68.00 56.41 43.59 57.52 42.48
56.55 43.45 49.06 50.94 42.86 57.14 100.00 0.00 0.00 100.00 11.49 88.51
41.67 58.33 52.17 47.83 26.83 73.17 61.54 38.46 57.69 42.31 33.33 66.67
20.00 80.00 34.38 65.62 0.00 100.00 59.26 40.74 100.00 0.00 43.43 56.57
50.00 50.00 25.53 74.47 35.56 64.44 84.42 15.58 47.53 52.47 0.00 100.00


Problem 2: From "Data Set 2," take each line and add up the all the odd fields and all the even fields per record. Then, as an added bonus, add up all the odd fields and all the even fields in all records. This was solved by the following awk statement (Note that, on the board, the sum for the first part of this problem was not printed as part of the solution, since it was being manipulated via an external array elsewhere within a script. For this example, I'm putting the totals for each line at the end of each line and anchoring them with text for easy distinction):

host # awk '{sum1=$1;sum2=$2;for (i=3;i<=NF;i++) {if ( i%2 ) {sum1 += $i; printf"%.2f ", $i}else {sum2 += $i; printf"%.2f ", $i}}printf"ODDS %.2f EVENS %.2f\n", sum1, sum2}' DATASET2

51.61 48.39 41.38 58.62 32.00 68.00 56.41 43.59 57.52 42.48 ODDS 284.75 EVENS 315.25
49.06 50.94 42.86 57.14 100.00 0.00 0.00 100.00 11.49 88.51 ODDS 259.96 EVENS 340.04
52.17 47.83 26.83 73.17 61.54 38.46 57.69 42.31 33.33 66.67 ODDS 273.23 EVENS 326.77
34.38 65.62 0.00 100.00 59.26 40.74 100.00 0.00 43.43 56.57 ODDS 257.07 EVENS 342.93
25.53 74.47 35.56 64.44 84.42 15.58 47.53 52.47 0.00 100.00 ODDS 243.04 EVENS 356.96


and for part 2 of problem 2 - to get the grand total of all even fields and grand total of all odd fields:

host # awk 'BEGIN{sum1=$1;sum2=$2}{for (i=1;i<=NF;i++) {if ( i%2 ) sum1 += $i;else sum2 += $i}}END{print "ODDS " sum1 " EVENS " sum2}' DATASET2

ODDS 1318.05 EVENS 1681.95


Problem 3: Given "Data Set 2," how could you divide every odd field by the grand total of all odd fields, and divide every even field by the grand total of all even fields (with minor modification to set the decimal precision from 2 to 4, since the resulting values will be well below 1% ;) - For example, you would want output that went through the data file and did "$1/1318.05 $2/1681.95, $3/1318.05..." etc. This can be accomplished by the following:

host # awk 'BEGIN{odds=1318.05;evens=1681.95}{for (i=1;i<=NF;i++) {if ( i%2 ) {odd=$i/odds; printf"%.4f ", odd}else {even=$i/evens; printf"%.4f ", even}}printf"\n";}' DATASET2

0.0348 0.0322 0.0392 0.0288 0.0314 0.0349 0.0243 0.0404 0.0428 0.0259 0.0436 0.0253
0.0429 0.0258 0.0372 0.0303 0.0325 0.0340 0.0759 0.0000 0.0000 0.0595 0.0087 0.0526
0.0316 0.0347 0.0396 0.0284 0.0204 0.0435 0.0467 0.0229 0.0438 0.0252 0.0253 0.0396
0.0152 0.0476 0.0261 0.0390 0.0000 0.0595 0.0450 0.0242 0.0759 0.0000 0.0330 0.0336
0.0379 0.0297 0.0194 0.0443 0.0270 0.0383 0.0640 0.0093 0.0361 0.0312 0.0000 0.0595


and here's an alternate way to get the same thing (combining problems 2 and 3 with the assumption that we don't know the exact values of the "odds" and "evens" variables I populated in the BEGIN section of problem 3):

host # echo `awk 'BEGIN{sum1=$1;sum2=$2}{for (i=1;i<=NF;i++) {if ( i%2 ) sum1 += $i;else sum2 += $i}}END{printf"%.4f %.4f", sum1,sum2}' DATASET2`|while read x y;do awk -v odds=$x -v evens=$y '{for (i=1;i<=NF;i++) {if ( i%2 ) {odd=$i/odds; printf"%.4f ", odd}else {even=$i/evens; printf"%.4f ", even}}printf"\n"}' DATASET2;done

0.0348 0.0322 0.0392 0.0288 0.0314 0.0349 0.0243 0.0404 0.0428 0.0259 0.0436 0.0253
0.0429 0.0258 0.0372 0.0303 0.0325 0.0340 0.0759 0.0000 0.0000 0.0595 0.0087 0.0526
0.0316 0.0347 0.0396 0.0284 0.0204 0.0435 0.0467 0.0229 0.0438 0.0252 0.0253 0.0396
0.0152 0.0476 0.0261 0.0390 0.0000 0.0595 0.0450 0.0242 0.0759 0.0000 0.0330 0.0336
0.0379 0.0297 0.0194 0.0443 0.0270 0.0383 0.0640 0.0093 0.0361 0.0312 0.0000 0.0595


And, hopefully, that's enough awk for now. Check out the Daniweb.com Shell Scripting Forum boards to see some of the great solutions other folks come up with (for some pretty bizarre problems) and, if it's just not your day, a few of my other monstrosity's ;)

Cheers,

, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Tuesday, November 18, 2008

Bash One-Liner Script To Produce Somewhat-Fancy Output Of Who's On Your Linux Or Unix Box

Hey there,

Today we're going to shoot out a quick one liner script that can come in handy from time to time. It doesn't fall under the "necessary" category (or, maybe not even the "useful" one ;), but it's nice to have for those times when you just don't feel like doing any extra typing or expending the effort required to separate the wheat from the chaff on a screen full of garbage output. That is, as I've always understood, one of the main reasons to script things out in the first place. The other reasons, like automation, efficiency, etc, are pretty much ignored here, even though we will be automating a repetitive action and that, by definition, will make our waste of company time more efficient. No matter how you look at them, automation and efficiency always seem to be a good thing ;)

This "script" is really just a simple pipe-slam so that we can figure out who's on the machine with us (my preference is for a script, but - as you'll soon see - this could just as easily be an alias, etc). Sure, we could just type "w" or "who," (and "w" does form the base of this bash one-liner script), but we'd like to have this whole thing look more personal. And by personal, I mean, we'd like to know who else is on other than us by UID or login name. The functionality (or relative merit) of this script depends heavily on the way in which users were created on your machine in the first place. If no "comment" (or "gecos") field is populated for users on your system, this command-chain is completely worthless.

For instance, assuming we had a user, with a login name of user1, logged in at the same time as us, with an entry that looked like this in /etc/passwd:

user2:x:32678:99::/home/user2:/bin/bash

and our /etc/passwd entry looked like this:

user1:x:32677:99:Mike The SysAdmin:/home/user1:/bin/bash

the command would pull no useful information for user2. So, if the output from w looked like this:

host # w
13:49:12 up 8 days, 3:41, 2 users, load average: 0.00, 0.14, 0.43
USER TTY LOGIN@ IDLE JCPU PCPU WHAT
user2 pts/0 08:44 5:03m 0.01s 0.01s -bash
user1 pts/1 09:05 0.00s 0.04s 0.00s w


our command would only produce output like this:

host # ./wdo.sh
Mike The SysAdmin


Whereas, if we added a comment field (perhaps via usermod -c "Bob The Guy Who Used To Be Anonymous" user2 or the chfn command), we would get nice output like the following:

host # ./wdo.sh
Mike The SysAdmin
Bob The Guy Who Used To Be Anonymous


and so forth, with users who had multiple sessions open being reported more than once. This script was written to give us a warm, fuzzy feeling, so seeing Bob's name five times is no big deal. If you want to use it for profiling purposes on a more heavily trafficed machine, there's always "sort."

Note, of course, that your version of Unix or Linux may produce slightly different output for the "w" command and xargs' -i flag may be "-I" (also, if, for some bizarre reason, your login names have spaces in them, just be sure to double quote the variable you define via xargs with the -i or -I flag. This should never happen). Basically, what I'm saying is, this script probably won't run correctly, exactly as it comes, on every single distribution of Linux and Unix out there :)

Enjoy the neighborhood watch :)

Cheers,

#!/bin/bash

#
# wdo.sh - More comments than code :)
#

w|awk '{print $1}' |xargs -ibing grep bing /etc/passwd|awk -F":" '{print $5}'



, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Tuesday, November 11, 2008

Determining Volume Group Disk Usage On AIX Unix Using Sh And Awk

Hey there,

Today's topic, and accompanying script, have to do with a more specific function already described in our series on working with AIX LVM (Actually, that link points to the last entry in the series. It's a strange thing about serialized content; the only way I can hook you up with a link that will get you links from part 4 to parts 3, 2 and 1 is to give you the last link. If only I could predetermine my following day's post URL without having to actually write the post... Actually, it probably can be done... I'll remind myself to work that into a post here soon. Hopefully I'll send myself an email to remind me before I forget ;)

This post has, loosely, to do with work. And I only mention this because I read in the online news that Google just canned some guy for writing about work in his blog! I'm not going to b.s. you and pretend like I read the entire thing, but, hopefully, he was posting company secrets. I'd hate to think what kind of an oppressive environment the corporate world would become if you could get your walking papers for ruminating over your day in an online diary. A lot of people have to work so much, they don't have much else to write about. Especially at Google. Why do you think they advertise all the games and cafeteria's and cots? Because it's a great place to work? They say; but perhaps it's because you're never ever going home again. The circle of madness has to be broken at some point ;)

In any event, working on an old AIX box, I was presented with a problem I hadn't considered for a while (on 5.x, anyway - I've been stuck in 3 and 4.x land for far too long ;) and, as I looked around for answers, I noticed that the information required to complete a pretty basic piece of work (and very useful, as well) just wasn't out there anywhere. Of course, the work involved using 2 (count 'em, 2 ;) separate commands, but... nothing. And that brings us to here.

The situation: Given a number of physical volumes, which have striped volume groups written across them, how can we figure out how much disk space (on how many different physical volumes and altogether) does that take up. I'm being intentionally vague, since the value we arrive at isn't as consequential as just being able to arrive at the value. Let's just say that we need to know because we need to replicate the disk space requirements elsewhere.

The answer: Surprisingly simple, once you get to it (although, perhaps because of my in-and-out AIX experience, confusing from time-to-time along the way). In order to extract this information, we just need to cruise through the following steps:

1. List out all available volume groups with the lsvg command:

host # lsvg
rootvg
number1vg
number2vg
...


2. Find out what physical volumes are associated with those volume groups using the same command and the "-p" switch. This time we'll need to name one of the volume groups. Steps from this point out would repeat for each individual volume group (and, later, physical volume) that comprise the logical and physical disk we're interested in (ellipses will be used to shorten lines for readability's sake):

host # lsvg -p rootvg
rootvg:
PV_NAME PV STATE TOTAL PPs FREE PPs FREE DISTRIBUTION
xdisk0 active ...
xdisk1 active ...


3. Then, get the number of physical partitions, and the set physical partition size for each physical volume listed out with the "lsvg -p" command above (The only two lines we really need from this output are the only two that aren't cropped with more ellipses), using the lspv command:

host # lspv xdisk0
PHYSICAL VOLUME: xdisk0...
PV IDENTIFIER: 000...
PV STATE: acti...
STALE PARTITIONS: 0 A...
PP SIZE: 64 megabyte(s) LOGICAL VOLUMES: 11
TOTAL PPs: 542 (34688 megabytes) VG DESCRIPTORS: 2
FREE PPs: 3....
USED PPs: 1....
FREE DISTRIBUTION: 1....
USED DISTRIBUTION: 0....


and we're all set :) Now, we just have a big sloppy mess of output to deal with. Lots and lots of lines of garbage, with the numbers we need sandwiched in, that we can manually add together. So, we'll move on to the natural next phase and script this out. For that volume group "rootvg" (for instance), rather than seeing all the above times 2, 3 or however much it is, this is much nicer to look at:

host # ./pvinfo.sh
Volume Group: rootvg
-----------
Physical Volume: xdisk0
Number of Physical Partitions: 542 Physical Partition Size: 64 Segment Total 34688 Mb
-----------
Physical Volume: hdisk1
Number of Physical Partitions: 542 Physical Partition Size: 64 Segment Total 34688 Mb
-----------
Physical Volume Grand Total : 69376 Mb
...


and so forth for all of our volume groups. Now we'll know how much disk space is allocated to our volume group, in total, and how much is allocated from each physical volume associated with the volume group. Feeling much better now ;)

Hope this helps you out some!

Cheers,


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!/bin/sh

#
# pvinfo.sh - get your AIX physical volume totals here!
#
# 2008 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

for x in `lsvg|awk '{print $1}`
do
echo "Volume Group: $x"
echo "-----------"
lsvg -p $x|sed 1d|while read one two three
do
if [ $two == "active" ]
then
echo "Physical Volume: $one"
lspv $one|awk 'BEGIN{sum1=0;sum2=0}{ if ( $1 ~ /TOTAL/ && $2 ~ /PPs/ ){ sum1 += $3 } else if ( $1 ~ /PP/ && $2 ~ /SIZE/ ) { sum2 += $3 }}END{sum3=sum1*sum2; print "Number of Physical Partitions: " sum1 " Physical Partition Size: " sum2 " Segment Total " sum3 " Mb";print "-----------"}'
fi
done
lsvg -p $x|sed 1d|while read one two three
do
if [ $two == "active" ]
then
lspv $one|awk 'BEGIN{sum1=0;sum2=0}{ if ( $1 ~ /TOTAL/ && $2 ~ /PPs/ ){ sum1 += $3 } else if ( $1 ~ /PP/ && $2 ~ /SIZE/ ) { sum2 += $3 }}END{sum3=sum1*sum2;print sum3}'
fi
done|awk '{ sum4 += $1 }END{print "Physical Volume Grand Total : " sum4 " Mb";print "-----------"}'
done


, Mike




Chris Gibson wrote in with this helpful shortcut. He's got quite a wealth of AIX info, and we've posted additional comments from him on our LVM Series page :)


BTW, you can also do the thing same with the lsvg command:

$ lsvg rootvg | grep 'TOTAL PPs'
VG PERMISSION: read/write TOTAL PPs: 1150 (73600 megabytes)

In the example above, we have 73600Mb in rootvg.

Cheers.

Chris


Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Wednesday, July 16, 2008

Perl and Bash Versions Of Binary To Decimal Conversion Script

Hey There,

As promised, in yesterday's post on converting binary values to decimal in C, today we're going to follow up with straight-up ports to Perl and shell. Actually, they'll be slightly different. If you check yesterday's post, for some reason I left in a variable called "difference" which was a part of the code I mentioned that I had originally written to pad 0's on the left hand side of a binary number less than 8 digits. Actually, it was noticed by an LXer, too, as well as the fact that I didn't specifically initalize "char binnumber" with a value. Whoops :) Special thanks to friends who pointed out that someone had commented on that. Not enough hours in the day to check everywhere. Thanks to the folks at LXer.com for doubling my virtual shame ;) Just kidding.

Anyway, I've mulled it over and I've decided to leave the original post with the error even though it could be fixed with a simple edit. I'm as fallible as the next guy (denying it would be pompous folly) and if I spent the rest of my life doing nothing but cleaning up my mistakes I'd never learn from them or (even worse) miss out on most of the good things life has coming around the bend. It can be a chore just thinking of something to write about once today; writing quick programs can be a real sleep-stealer. But I'm going waaaay off-topic.

Both of today's scripts work exactly as they did in yesterday's post (with the bonus that these programs will know whether your variables are integers or characters just by defining them (No initialization necessary). Please check out that conversion program post for specifics on how the program works, it's purposefully imposed limitations, etc.

Both scripts (Perl and shell -- and I think this is the first time I've ever thrown two scripts into one post, so apologies if the Blogspot code formatting is worse than usual ;) run just like yesterdays code, except I've named them differently. You can, of course, change the names to whatever you want:

host # ./bin2dec.pl

or

host # ./bin2dec.sh

and both produce output that's exactly the same:

host # $ ./bin2dec.pl

8 Digit Binary Number?
10010010

Binary 10010010 equals Decimal 146!


We're not going into an explanation of porting at this point (we're following that on a separate path in our posts on porting between Perl, shell and Awk), but you should be able to see a lot of similarities between the code.

Note that, for today, the Perl script will come first and then the shell script. They should be easy to discern. We'll see... this is my first try at doing a double-script ending. Maybe one day they'll let me do attachments (If the GoogleBot can hear me, I'll gladly pay for that :)

Cheers,


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!/usr/bin/perl

# bin2dec.pl - Convert 8 digit binary numbers
# to decimal numbers
#
# 2008 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

$total = 0;

print "\n8 Digit Binary Number?\n";
chomp($binnumber = (<STDIN>));
@binnumber = split(//, $binnumber);
$length = @binnumber;

if ( $binnumber[7] == 1 ) {
$total += 1;
}
if ( $binnumber[6] == 1 ) {
$total += 2;
}
if ( $binnumber[5] == 1 ) {
$total += 4;
}
if ( $binnumber[4] == 1 ) {
$total += 8;
}
if ( $binnumber[3] == 1 ) {
$total += 16;
}
if ( $binnumber[2] == 1 ) {
$total += 32;
}
if ( $binnumber[1] == 1 ) {
$total += 64;
}
if ( $binnumber[0] == 1 ) {
$total += 128;
}

print "\nBinary $binnumber equals Decimal $total!\n";
exit(0);





#!/bin/bash

# bin2dec.sh - Convert 8 digit binary numbers
# to decimal numbers
#
# 2008 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

total=0

echo -e "\n8 Digit Binary Number?\n"
read number
length=${#number}

set -a binnumber
for x in $(seq 0 $((${#number} - 1)))
do
binnumber[$x]=${number:$x:1}
done

if [ ${binnumber[7]} -eq 1 ]
then
total=$((total + 1))
fi
if [ ${binnumber[6]} -eq 1 ]
then
total=$((total + 2))
fi
if [ ${binnumber[5]} -eq 1 ]
then
total=$((total + 4))
fi
if [ ${binnumber[4]} -eq 1 ]
then
total=$((total + 8))
fi
if [ ${binnumber[3]} -eq 1 ]
then
total=$((total + 16))
fi
if [ ${binnumber[2]} -eq 1 ]
then
total=$((total + 32))
fi
if [ ${binnumber[1]} -eq 1 ]
then
total=$((total + 64))
fi
if [ ${binnumber[0]} -eq 1 ]
then
total=$((total + 128))
fi

echo -e "\nBinary $number equals Decimal $total!\n"
exit 0


, Mike

Tuesday, July 15, 2008

Converting Binary Numbers To Decimal The Hard Way On Linux Or Unix

Hey There,

If you recall a while back, we looked at using Perl's "unpack" function to easily convert binary values to decimal and convert decimal back to binary. Those were both (some folks may consider) relatively sophisticated methods of tackling the problem. Although, once you understand how "unpack" works, the first becomes incredibly simple to use and understand. The other one may always be a little awkward.

Today we're going to look at doing binary to decimal conversion using a less "worldly" method ;) The program we have for you today (and I refer to it as a program since it's written in C) attacks the problem more naturally. And, by naturally, I mean that it should make sense to anyone at its core (assuming they understand the C programming language). The method of execution is not the most efficient, but I think it's the most "human readable." In a future post, we'll definitely convert it to Perl, shell and Awk. And, maybe before then, we'll get to the next part in our ongoing series on Perl, shell and Awk porting. We'll get there eventually. If I didn't have so many different things to write about, I could bore you to tears with that stuff (if I haven't already ;)

Hope you enjoy the program. You can build it easily, using a compiler like gcc in this fashion:

host # gcc -o bin2dec bin2dec.c

and run it just as easily:

host # $ ./bin2dec

8 Digit Binary Number?
10010010
<-- I think there's a subtle homage to Rush in there - just forget about the ending 0 ;)

Binary 10010010 equals Decimal 146!

The only catch, which the executable program will prompt you with, is that (in order to keep it simple) it's limited to 8 digit binary numbers and expects an 8 digit binary number as input. This means that binary 1 would return 128 (10000000) instead of 1 (00000001). Both symptoms can be fixed by adding extra code to pad zeros on the left hand side, but I felt, after seeing the resulting code, that including it would take away from the basic gist of this post, which is that C, Perl, shell and Awk are totally accessible to "anyone" who wants to learn them. I wanted to put something out that looked as little like a completely foreign language as possible. It is my philosophy that anyone can learn how to code and/or use the Linux or Unix Operating System(s).

Of course, if "everyone" loses their irrational "fear of computers" and does start doing this stuff well, I'll end up being a fry-guy at McDonald's in about 10 years ;)

Cheers,


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

/********************************************
* bin2dec - Convert 8 digit binary numbers *
* to decimal numbers *
* *
* 2008 - Mike Golvach - eggi@comcast.net *
* *
********************************************/

/* Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License */

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

main()
{

char binnumber[8];
int length;
int difference;
int total = 0;

printf("\n8 Digit Binary Number?\n");
scanf("%s", &binnumber);
length = strlen(binnumber);
if ( length < 8 ) {
difference = -(length - 8);
}
if ( binnumber[7] == '1' ) {
total = total + 1;
}
if ( binnumber[6] == '1' ) {
total = total + 2;
}
if ( binnumber[5] == '1' ) {
total = total + 4;
}
if ( binnumber[4] == '1' ) {
total = total + 8;
}
if ( binnumber[3] == '1' ) {
total = total + 16;
}
if ( binnumber[2] == '1' ) {
total = total + 32;
}
if ( binnumber[1] == '1' ) {
total = total + 64;
}
if ( binnumber[0] == '1' ) {
total = total + 128;
}
printf("\nBinary %s equals Decimal %d!\n", binnumber, total);
return 0;
}


, Mike

Tuesday, July 8, 2008

Double Spacing In Awk, Perl and Shell on Linux and Unix

Hey there,

Surprisingly, yesterday's post on multiline spacing with sed on Linux and Unix got some reponse. Enough so, that I figured I'd follow up today and answer the call for equal representation for Perl, awk and the plain old shell (pick one, any one ;)

This post is going to be much the same as yesterday's, except with a few different tricks using a few different languages, rather than just focusing on one (sed). In fact, except for the fact that I'm mentioning sed every fifth word or so, and we're going to kick things off with a brief review of yesterday's simplest command, today should be a sed-free post ;)

First, we'll look at the file itself (appropriately named FILENAME):

host # cat FILENAME
this is the beginning
and now we're in the middle
this is the end


As you recall, from yesterday's post on using sed to handle multiline spacing, we could easily double space this file, using sed, with the following command <-- Note that I won't be repeating the output any more,
since it's the same for every command to follow and we'll assume, from checking out the above mentioned post, that triple-spacing, etc, is an easy concept to grasp once you've got the "double space" down:

host # sed G FILENAME
this is the beginning

and now we're in the middle

this is the end

host #


Awk was the next obvious candidate for "character management." The easiest (read: shortest) way I could figure, find and confirm, was this obvious statement:

host # awk '{print $0"\n"}' FILENAME

I also saw this solution floating around everywhere, but am jailed to a Solaris 8 box as I write. It doesn't work on the native awk, here, but perhaps this does work on Linux
or with Gnu awk. I found that it definitely does work with nawk on Solaris:

host # awk '1;{print ""}'

Perl came up next. It's a heavy hitter, compared to sed and awk, but actually just about as compact on the command line:

host # perl -pe '$_ .= "\n"' FILENAME

Then I decided to check out the shell (which means pretty much every command available) and quickly realized that anything you could really do involved some other basic editing command (or editor) like ed or similar programs. Not really novel. Just an endless parade of variations on the same theme. I decided to just go with this command line, since it's just using the shell and not overtly pulling in any external programs, to get the job done:

host # while read;do echo "$REPLY\n";done<FILENAME

and then this line, too, since (even though it's more convoluted) it's just a little bit shorter:

host # while read x;do echo "$x\n";done<FILENAME

Hopefully that wraps up this whole business with line spacing in files on Linux and Unix. I'm certainly always receptive to additional comments, but, hopefully we've said all that really needs to be said on this topic and can move on away from it tomorrow ;)

Cheers,

, Mike

Monday, June 30, 2008

Simple Cumulative Math Using Awk On Unix or Linux

Hey There,

I'm off to start a new work assignment today (after sleeping in late for a week), so, as you're reading this I may be trying not to fall asleep on the train or wishing I had slept more and/or was dead ;) In any event, this week, I thought we'd start getting back to that interstitial series on porting between shell, awk and Perl on Linux or Unix and, by way of getting back into it, make this post (at least a little bit) resemble the last post, which dealt with simple arithmetic.

One of the questions I see floating around the boards a lot has to do with using awk to calculate cumulative (or incremental) sums within a file. So, for a simple example, if a user had a file called "numbers" which contained the following:

host #cat numbers
a 4
b 2
c 8
d 57
e 12
f 8967
g 3
h 58
i 3


they'd want awk to read through that file, and give the total result of all the numbers in column 2. For kicks, they may also want to print each line in the file as it gets processed (at least until they're satisifed that it's doing what they want. After that it gets to be a consumption of screen space for no reason)

Our attached shell script (which only runs awk inside it and accepts a filename as an argument) does just that. Note that it doesn't do any error checking, and assumes you know that your input file should be of the form: one pair per line of "name" [space or tab] "number," like above. It can be run very simply from the command line, and should provide output, like so:

host # ./sum.sh numbers
a numvalue: 4
b numvalue: 2
c numvalue: 8
d numvalue: 57
e numvalue: 12
f numvalue: 8967
g numvalue: 3
h numvalue: 58
i numvalue: 3
Sum total: 9114


Of course, this script can also be written as a one-liner, as long as you redirect the input to it that it requires, like so:

host # awk 'BEGIN {name="testcase";oldname="testcase"}{name=$1;if (name != oldname || oldname != "testcase") print name " numvalue: " $2; sum=0;finalsum += $2;oldname = name} END {print "Sum total: " finalsum}' numbers
a numvalue: 4
b numvalue: 2
c numvalue: 8
d numvalue: 57
e numvalue: 12
f numvalue: 8967
g numvalue: 3
h numvalue: 58
i numvalue: 3
Sum total: 9114


Basically, all we're doing is going through each line of the file and adding the numeric value of each line to the numeric value of the total until the input file ends. Of course, you can modify this slightly to make it do any sort of arithmetic operation you require. Multiplication, division, subtraction, etc. At least, as much as awk will allow ;)

Hope you're enjoying this more than I'm probably enjoying my morning. And, in both cases, there's probably a better, and more efficient way to do this ;) Here's to that!

Cheers,


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!/bin/sh

#
# sum.sh
#
# 2008 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

file=$1
awk 'BEGIN {name="testcase"
oldname="testcase"}
{name=$1
if (name != oldname || oldname != "testcase") {
print name " numvalue: " $2
sum=0}
finalsum += $2
oldname = name}
END {print "Sum total: " finalsum}' $file


, Mike

Thursday, May 29, 2008

Simple Shell One-Liner To Enumerate File Types In Linux and Unix

Hey there,

Lately, we've been focusing a lot on Perl "one liners," from mass file time syncing to name and IP resolution and I thought it was only fair that we should write a post about a shell "one liner" for once. After all, most standard Unix and Linux shells are perfect for that purpose :)

Here's a very quick way to take an inventory of all the different file types (including directories, sockets, named pipes, etc) that exist in a given directory tree and provide a tally of each file type. I'm not entirely sure that I care if I have 15 ASCII text files and 2 Perl scripts in my current working directory, but this little piece of code must be able to help someone somewhere accomplish something, even if it is only to use as a smaller part of a larger organism ;)

This works in pretty much any standard shell on every flavour of Linux and/or Unix I've tested (ash, sh, bash, jsh, ksh, zsh, even csh and tcsh, which is huge for me since I never use those shells. One day, soon, I will redouble my efforts and just learn how to use them well, which, hopefully, won't result in my writing a whole bunch of posts about "cool" stuff that everyone has known about for the past few decades ;).

This one-liner could actually be written as a script, to make it more readable, like this:

#!/bin/sh
find . -print | xargs -I var file "var"|
awk '{
$1="";
x[$0]++;
}
END {
for (y in x) printf("%d\t%s\n", x[y], y);
}' | sort -nr


But, since I'm a big fan of brevity (which is about as far away from obvious as possible if you consider my writing style ;), I would run it like this:

host # find . -print|xargs file|awk '{$1="";x[$0]++;}END{for(y in x)printf("%d\t%s\n",x[y],y);}'|sort -nr

In my terminal, that all comes out on one line :) And here's the sort of output you can expect:

host # find . -print|xargs file|awk '{$1="";x[$0]++;}END{for(y in x)printf("%d\t%s\n",x[y],y);}'|sort -nr
23 Bourne-Again shell script text
11 ASCII text
10 perl script text
5 pkg Datastream (SVR4)
4 directory
4 ASCII English text
2 UTF-8 Unicode English text, with overstriking
2 Bourne shell script text
1 RPM v3 bin i386 m4-1.4.10-1


and, just to confirm the file count, we'll change the command slightly (to total up everything, instead of being particular -- another "one-liner" that's, admittedly, completely unnecessary unless you're obsessive/compulsive like me ;) and compare that with a straight-up find:

host # find . -print|xargs file|awk 'BEGIN{x=0}{x++}END{print x}'
62
host # find .|wc -l
62


Good news; everything appears to be in order! Hope this helps you out in some way, shape or form :)

Cheers,

, Mike

Wednesday, May 28, 2008

Simple Arithmetic In Bash, Perl and Awk - More Porting

Greetings,

Today we're going to continue along on our series of posts dealing with porting code between the bash shell, Perl and awk. In previous posts, we've looked at the basics regarding simple string variables, simple one-dimensional arrays and associative arrays (sometimes referred to as hashes or "lookup tables.").

Before we move on to logical programming constructs (such as if-conditionals and while-loops), it's important to go over a few other basic concepts that require translation in order to work in the same manner in all three languages. Today we're going to demonstrate how each of bash, Perl and awk deal with simple arithmetic. Note that we won't be dealing specifically with floating point math (although it is possible to do) since that's slightly beyond the scope of this article (but it will be -- huge hint -- the subject of our next post in this series... variable scope, that is ;)

For our purposes today, we're going to assume that we need to solve five different arithmetic equations in each of our three languages. And, coincidentally enough, all five equations need to serve a distinctly different arithmetic purpose. We're going to have to take two integers and perform addition, subtraction, multiplication and division on them, and also extract the remainder of any imperfect divisions (defined herein as any division which doesn't have a remainder of 0). Note that, for all of our "bash" examples, the spaces (or lack thereof) in the equations are "required." Perl and awk will produce results with or without spaces between the operands.

1. Bash: In the bash shell, all of these actions are very simple to perform, and you have a more than a few options at your disposal depending on how you prefer to do them. The one way you can perform shell arithmetic that will work in older versions of the bash shell (or most any other shell) is to use the "expr" commmand. While this is, technically, an entirely separate program, it can come in handy if you get ahold of an older shell that can't perform arithmetic on its own. The syntax for our equations would be the following (We'll be assuming that the side explanations will be the same for Perl and awk to save on space):

host # expr 9 + 2
11
host # expr 9 - 2
7
host # expr 9 \* 2
18
host # expr 9 / 2
<--- Here you can see a limitation of simple integer math in the shell. 9 divided by 2 should be 4.5, but the shell doesn't understand the fraction.
4
host # expr 9 % 2
<--- And here's the reason we want to see the remainder of that division. This shows us that 1 integer was lost in the imperfect division.
1

The bash shell, however, will allow you to do simple arithmetic in a much more simplistic way. And this is it (we'll use the shell built-in "echo" to print the output to the screen):

host # echo $((9+2))
11
host # echo $((9-2))
7
host # echo $((9*2))
18
host # echo $((9/2))
4
host # echo $((9%2))
1


2. Perl: Perl, as we've mentioned in previous posts, provides easy access to the shell via the backtick operators and "system" function, but there's almost no need to ever use those, since Perl can do simple arithmetic on its own. In fact, depending upon how heavily you use a "system" resource from within a Perl program, the slower and more cumbersome that program will become. Using Perl's built-in functions and methods is almost always more efficient.

Here's an example of how we'd do the same arithmetic with Perl, using the command line execution statement (-e flag) method (again, we'll use a print function to spit the output to the terminal):

host # perl -e 'print 9 + 2 . "\n";'
11
host # perl -e 'print 9 - 2 . "\n";'
7
host # perl -e 'print 9 * 2 . "\n";'
18
host # perl -e 'print 9 / 2 . "\n";'
<--- Note, here, how Perl naturally deals with fractions!
4.5
host # perl -e 'print 9 % 2 . "\n";'
1


3. Awk: Awk makes performing arithmetic operations incredibly easy, as well. It, like Perl, also understands simple fractions and accounts for simple floating point arithmetic right out-of-the-box:

host # echo |awk '{print 9+2}'
11
host # echo |awk '{print 9-2}'
7
host # echo |awk '{print 9*2}'
18
host # echo |awk '{print 9/2}'
4.5
host # echo |awk '{print 9%2}'
1


And, that's all there is to it. As you can see, the difference between performing simple arithmetic in all three languages isn't that great. As we continue to examine porting code between these languages, you'll notice a lot of similarities (and a few minor differences ;) which will make the translation of one language to another very simple for you with a little practice and patience.

Our next porting post will deal with variable scope, which we'll both define and demonstrate .

Until then!

, Mike

Sunday, May 18, 2008

Doing Search And Replace In Multiple Files With Unix and Linux Perl - Easy Or Hard?

Hey There,

For this weeks "Lazy Sunday" post we're going to take a look at the versatility of Perl on Linux or Unix. While I'm fairly certain there's little argument that it's the best tool for most "extraction" and "reporting" functions when used in complicated situations, it's always been more interesting to me because of the wide range of ways you can complete any sort of task.

Today we're going to take a look at two different ways to do search and replace in multiple files using strictly Perl. The first way will be obnoxiously long and the second way will be almost invisible ;)

For both situations, we'll assume that we have 15 files all in the same directory. We'll also assume that we're logged into our favorite flavour of Linux or Unix OS and, coincidentally, in the same directory as those files. All the files are text files and are humungous. And, finally, all of the files are stories where the main character's name is Waldo, they've never been published and the writer's had a change of heart and decided to name his main character Humphrey. It could happen ;)

1. The hard way (or, if you prefer, the long way):

We'll write a script to read in each file and scour it, line by line. For lines on which the name Waldo appears, we'll replace that with Humphrey. We're taking into account, also, that Waldo may be named more than once on any particular line and that the name Waldo may have accidentally been mistyped with a leading lowercase "w," which needs to be corrected. That script would look something like this:

#!/usr/bin/perl

#
# replace_waldo.pl - change Waldo to Humphrey in all files.
#
# 2008 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

@all_files = `ls -1d *`;
$search_term = "Waldo";
$replace_term = "Humphrey";

foreach $file (@all_files) {
$got_one = 0;
chomp($file);
open(FILE, "<$file");
@file=<FILE>;
close(FILE);
foreach $line (@file) {
if ( $line =~ /Waldo/i ) {
$line =~ s/Waldo/Humphrey/gi;
$got_one = 1
}
}
if ( $got_one ) {
open(NEWFILE, ">$file.new");
print NEWFILE @file;
close(NEWFILE);
rename("$file.new", "$file");
}
}


2. The easy way (or, again, the short way):

Assuming the exact same convoluted situation, here's another way to do it (which we've covered in a bit more detail in this older post on using Perl like Sed or Awk):

From the command line we'll type:

host # perl -p -i -e 's/Waldo/Humphrey/gi' *

And we're done :)

Of course, the longer method is better suited for situations in which there are other extenuating circumstances. Or, perhaps, even more work to do. For the sort of limited situation we've laid out today, I will almost always go with the second method (Who wants pie? :)... Unless I have lots of time on my hands ;)

Cheers,

, Mike

Friday, May 16, 2008

Porting Associative Arrays Between Perl, Shell and Awk

Hey There,

And, for the last time (this week) we're back to porting :) One thing you might have noticed, in the title of today's post, is that the C programming language has been dropped. We received some feedback, and also generally agree, that throwing C in with Perl, Shell and Awk creates a layer of confusion that distracts from the point of these posts. Which is, of course, to demonstrate how simply one can use concepts, and apply them easily, with a little translation, between three very useful Unix and Linux programming (or scripting) languages.

We'll leave the original posts alone, so if you go back to revisit our original post regarding simple string variables and its follow-up that dealt with simple arrays, please just ignore all that stuff about C. If there's sufficient interest at a later time, we'll write up a series of posts on porting between (for instance) Perl and C and try to contain the amount of collateral damage ;)

Today, we're going to look at associative arrays (which are generally referred to as "Hashes" in Perl and as "lookup tables" from time to time) and how we can define, add value to, and extract value from, them in Perl, bash and awk.

The main differences between a "regular" array and an associative array is, at its most basic, found in the way that the array is indexed and the way in which you can add and extract value from the array. This is why I noted that, in bash, the only type of arrays available (at this point) are "regular" or "one dimensional" arrays, which we looked at in our last post on array porting ( Please note that I'm stuck using version "2.05b.0(1)" and am unaware of any newer release (up to bash 3.2) which directly supports this functionality. I "am" looking forward to it, though :)

The good news is that there is a hack to get around this, and emulate associative arrays, if you want to drive yourself crazy. We will definitely follow up this post with a post regarding how to do that (it'll be a post in and of itself, so we'll not belabour that point any longer, here). Also, in awk, there's, technically, no such thing as a "regular array." If you dump an Awk array, there's no guarantee that the contents will come out in the order you expect (which is also true of the Perl hash) and you can also use keys with them, instead of being limited to indexes. This will begin to make sense, if it doesn't already, as we go along. Terminology being what it is, I may have upset a lot of people already ;)

And, now that I've dug myself a deep enough hole, let's get started with associative arrays ;)

The associative arrray is sometimes defined as a "lookup table" for good reason. Compared with "associative array" and "hash," it's a name that's more descriptive of how the associative array works. Basically, on the left hand side of any assignment (the variable before the value) you have the name of the associative array along with a "key," like: $bob{"key"} - On the right hand side of the equation you have a simple value. You can see how the term "lookup table" makes the most sense as, in this case, if you wanted to look up the value of "key" you could find it in the associative array named "bob" simply by naming it. The associative array can also be thought of as having "keys" and "values," rather than "indexes" and "values," like regular, one dimensional, arrays have.

Since Bash only supports one-dimensional arrays up to (at least) version 2.05b.0(1), none of today's lesson applies. We will, however, definitely follow up with a post dedicated to "faking" associative arrays with bash.

1. Defining, Initializing or Declaring an associative array. As was the case with simple variables and arrays, no explicit declaration of an associative array is absolutely necessary in either of our (now) two languages:

Ex: We need to define an associative array called MySimpleHash. Even though it's unnecessary, we could do so like this:

In Perl: Just type "%MySimpleHash;" - The % symbol indicates an associative array (or hash) in Perl, as opposed to the $ sign, which indicates a scalar (or simple, or string) variable and the @ symbol which indicates an array. Perl hashes can also be created by simply defining their elements on-the-fly.

In Awk: Just type "declare MySimpleHash" - Again, associative arrays in Awk can be created by referencing their components and work exactly like one-dimensional arrays.

2. Assigning values to the associative array. This is very straightforward in both of our two remaining languages:

Ex: We want to assign the keys "MySimpleKey0," "MySimpleKey1" and "MySimpleKey2" ( with values, in order, of "MySimpleValue0", "MySimpleValue1," and "MySimpleValue2") to the associative array named MySimpleHash (Note that any values that contain spaces should be quoted - it's actually good practice to quote any string that is a being used as a key or a value in an associative array. This is generally not necessary for integer values).

In Perl: Just type "$MySimpleHash{"MySimpleKey0"} = MySimpleValue0; $MySimpleHash{"MySimpleKey1"} = MySimpleValue1; $MySimpleHash{"MySimpleKey2"} = MySimpleValue2;" - Spaces between the variable, "=" sign and value are optional. Note that we have to use the $ symbol when referring to an element of a Perl hash, while we use the % symbol to refer to the entire hash (or associative array. Same thing. But you know that by now ;) Also, last thing, notice that the square brackets, used to refer to regular array indexes, are replaced by curly brackets.

In Awk: Just type "MySimpleHash["MySimpleKey0"] = "MySimpleValue0"; MySimpleHash["MySimpleKey1"] = "MySimpleValue1"; MySimpleHash["MySimpleKey2"] = "MySimpleValue2";" - Spaces between the variable, "=" sign and value are not, technically, necessary, but recommended. Also, note that all of the "MySimpleKey" keys, and "MySimpleValue" values, are placed within double quotes in the assignment. This is sometimes necessary for string values, but usually not always necessary for numeric values.

3. Extracting the value from your simple associative array. This is no longer "trivial," but still not too terribly difficult to do. Let's look some stuff up in these tables :)

Ex: We want to print the value of all of the keys of the MySimpleHash associative array. This is also fairly simple in our dwindling nation of two languages ;) Note that we will be iterating over the array key/value pairs in order to print them all out. This is where you'll notice one very specific characteristic of the associative array (or hash). The associative array does it's own indexing based on an internal algorithm and may not spit out the same values in the same order every time you dump the contents. This is done, by the programming language, for maximum efficiency with regards to information storage and retrieval (with the assumption that you'll be looking for a particular "key"'s value, I suppose).

In Perl: Just type "while (($Key, $Value) = each %MySimpleHash) { print "$Key equals $MySimpleHash{$Key}\n";}"
- Note that the $ character needs to precede the variable name when you want to retrieve any of an associative array's key or value elements. Also, when iterating over the hash, you need to refer to the hash directly with the % prefix (printing %MySimpleHash would print out all of that hash's elements - generally all squished together with no separating space) - The \n, indicating a carriage-return, line-feed or new-line isn't necessary, but is nice if you don't want your output on the same line as your next command prompt:

host # perl -e '$MySimpleHash{"MySimpleKey0"} = MySimpleValue0; $MySimpleHash{"MySimpleKey1"} = MySimpleValue1; $MySimpleHash{"MySimpleKey2"} = MySimpleValue2;while( ($key, $value) = each %MySimpleHash ) { print "SimpleKey: $key, SimpleValue: $value.\n";}'
SimpleKey: MySimpleKey0, SimpleValue: MySimpleValue0.
SimpleKey: MySimpleKey2, SimpleValue: MySimpleValue2.
SimpleKey: MySimpleKey1, SimpleValue: MySimpleValue1.


For a goof, let's print out the entire hash at once, so you can see how the indexing is done automatically by Perl (i.e. it might not come out in the same order that the data was logically entered by us) :

host # perl -e '$MySimpleHash{"MySimpleKey0"} = MySimpleValue0; $MySimpleHash{"MySimpleKey1"} = MySimpleValue1; $MySimpleHash{"MySimpleKey2"} = MySimpleValue2;print %MySimpleHash;print "\n";'
MySimpleKey0MySimpleValue0MySimpleKey2MySimpleValue2MySimpleKey1MySimpleValue1


And, if you can see in the crunch there, it has indeed ordered our key/value pairs as 0, 2, 1, instead of the 0, 1, 2 that you would expect from a regular array!

In Awk: Just Type "for (x in MySimpleHash) { print x "=" MySimpleHash[x]; }" - Note that the $ or % symbol "must not" precede the variable name, or key name, when you want to get the value. Note that, just like regular arrays, awk associative arrays need to be iterated over to be entirely printed out. Again, here, we should see how awk has decided to index our key/value pairs, which might be different than the order in which we entered them (you'll generally see this more if you mix numeric and alpha keys in your awk associative array (here, we seem to get lucky :) :

host # echo |awk '{MySimpleHash["MySimpleKey0"] = "MySimpleValue0"; MySimpleHash["MySimpleKey1"] = "MySimpleValue1"; MySimpleHash["MySimpleKey2"] = "MySimpleValue2";for (x in MySimpleHash) { print x "=" MySimpleHash[x]; }}'
MySimpleKey0=MySimpleValue0
MySimpleKey1=MySimpleValue1
MySimpleKey2=MySimpleValue2


An interesting side fact about awk associative arrays is that, even if they come out in the order you expect, they may not be indexed exactly as you indexed them. For instance, when you enter the first, second and third value, you would expect them to occupy indexes 0, 1 and 2 from an regular awk array. An awk associative array may have those values indexed as 0,44 and 117. Let's see what happens if we pull keys 0, 1 and 2 out from MySimpleHash:

host # echo |awk '{MySimpleHash["MySimpleKey0"] = "MySimpleValue0"; MySimpleHash["MySimpleKey1"] = "MySimpleValue1"; MySimpleHash["MySimpleKey2"] = "MySimpleValue2";print MySimpleHash[0] MySimpleHash[1] MySimpleHash[2];}'

host #


Nothing. Goose eggs; as expected. Since awk creates the association for you, the simple numeric indexing won't work to retrieve the value for, say, "MySimpleKey2." If you want to force numeric indexing, you just need to make sure that all of your indexes are numbers (which is how we emulated a regular array in our previous post on working with regular arrays). Note, also, that if you want to make sure that a number you enter as an index is treated like a key in a key/value pair, the simplest way to do this is to enclose it in "double quotes."

Sadly, even though this article ran a bit long, there are still a lot of "little things" about associative arrays (or hashes, lookup tables, or whatever you prefer to call them) that can be explored. Hopefully, you're encouraged to get down to the nitty-gritty and rise above the attempted basic-ness of this post (Now I'm starting to make up words ;)

In our next addition to this threaded series of posts, we'll start looking at programming constructs (loops, conditionals, etc) and explore how we can use the basic variable knowledge we've acquired so far to get some real work done now(after all, that's less work for us to do later ;)

Cheers,

, Mike

Wednesday, May 14, 2008

Working With Arrays - Porting Between Linux Or Unix Using Bash, Perl, C and Awk

Greetings,

Back to porting some more :) Building on our posts starting from the shebang line, followed, somewhat logically by a post on working with simple variables, today we're going to move on to the next step: Defining, populating and extracting the values from simple array variables.

The array variable is another basic building block of most shell scripts or code. Put simply, an array is just a collection of the simple variables we looked at in our last post on porting.

The technical definitions, especially as they apply to each of our four languages (bash, Perl, awk and C) are beyond the scope of this series of posts (for now). The details are important, but they're useless if you don't know the basics. To put it in another light, when you learn a foreign language (German, for example), it's more important that you understand basic concepts of the language, and how to use those simple phrases, than it is for you to be able to break down the subtle differences between the gender and tense of each word within the context of a sentence. The folks in Germany will know you need to go to the bathroom no matter how poor your grammar is, as long as you can spit out a few key words that indicate your need to find a restroom immediately ;)

So, let's get started with arrays:

Arrays, as we mentioned, are simply collections of simple variables. For instance, taking from our previous example, if we have a variable x, that has a value of y (x=y), then we have a simple variable. Arrays provide a way to group collections of simple variables. So you could have a number of variable/value pairs (x=y, a=b, c=d, e=f, etc), or simply a collection of values, that can all be referred to by one variable name: the array name (e.g. array b = x=y and a=b and c=d and e=f). More cryptic than a simple variable explanation, but (even if it's not right now) simple to understand once you get the hang of it.

1. Defining, Initializing or Declaring an array. As was the case with simple variables, with a simple array, except in C (of course), no explicit declaration of an array is absolutely necessary:

Ex: We need to define an array called MySimpleArray. This is trivial in all four languages:

In Bash: Just type "declare -a MySimpleArray" (again, you can also use "typeset -a"). This is not absolutely necessary, as you can create an array simply by defining a part of it (e.g. MySimpleArray[0]="bob" would create the MySimpleArray array with one value)

In Perl: Just type "@MySimpleArray;" - The @ sign indicates an array in Perl, as opposed to the $ sign, which indicates a scalar (or simple, or string) variable. Perl arrays can also be created by defining their elements.

In Awk: Just type "declare MySimpleArray" - Again, arrays in Awk can be created by referencing their components.

In C: You "need" to declare/initialize your array (and its size) before you can use it. As noted in our last post, a simple string variable, in C, is actually an array of the type "char."

So, just like when you declared the "simple variable" MySimpleVariable, you'll use the exact same syntax, since that was, technically, an array: "char *MySimpleArray;" (This, again, generally needs to be followed by a declaration of the size/memory-allocation-requirement of the string, like "MySimpleArray = (char *)malloc(8*sizeof(char));" for an 8 character array).

Also, in C, if you want to declare an integer array, you would do it in this fashion (although we're not going to drill too far into this since it pulls away from the commonality of all the other examples): "int MySimpleArray[8];" for an eight integer array.

2. Assigning values to the simple array. This is very straightforward in all of our four languages:

Ex: We want to assign the values "MySimpleValue0", "MySimpleValue1," and "MySimpleValue2" to the simple array named MySimpleArray (Note that any values that contain spaces should be quoted - it's actually good practice to quote any string that is a being used as a value in an array. This is generally not necessary for integer values). Note that our instructions for creation here today are based on simplicity, and not efficiency. There are quicker ways to define arrays all at once (and print them all at once, when we extract the values from the array variables), but we'll leave that for another time. Also note that, in most arrays, the first element is numbered 0, rather than 1.

In Bash: Just type "MySimpleArray[0]=MySimpleValue0; MySimpleArray[1]=MySimpleValue1; MySimpleArray[2]=MySimpleValue2" - Spaces between the variable, "=" sign and value are not permitted.

In Perl: Just type "$MySimpleArray[0] = MySimpleValue0; $MySimpleArray[1] = MySimpleValue1; $MySimpleArray[2] = MySimpleValue2;" - Spaces between the variable, "=" sign and value are optional. Note that we have to use the $ symbol when referring to an element of an array, while we use the @ symbol to refer to the entire array.

In Awk: Just type "MySimpleArray[0] = "MySimpleValue0"; MySimpleArray[1] = "MySimpleValue1"; MySimpleArray[2] = "MySimpleValue2"" - Spaces between the variable, "=" sign and value are not, technically, necessary, but recommended. Also, note that "MySimpleValue0," "MySimpleValue1," and "MySimpleValue2" are placed within double quotes in the assignment. This is sometimes necessary for string values, but usually not for numeric values.

In C: Just type: "MySimpleArray = "MySimpleValue";" If your array is not simply a char (as we're using in our example today), you do not need to use quotes. For an integer array, you would add values like this: "MySimpleArray[] = {0,1,2};" <--- Again, apologies if these C integer array side notes are distracting. Just ignore them ;)

3. Extracting the value from your simple array. It's time to collect :)

Ex: We want to print the value of the MySimpleArray elements. This is also fairly simple in all four languages:

In Bash: Just type "echo ${MySimpleArray[0]};echo ${MySimpleArray[1]};echo ${MySimpleArray[2]}" - Note that the $ character needs to precede the variable name when you want to get the value and that the {} brackets around the array name and subscript (in [] brackets) are required. Printing ${MySimpleArray[@]} would print out all elements.

host # echo ${MySimpleArray[0]};echo ${MySimpleArray[1]};echo ${MySimpleArray[2]}
MySimpleValue0
MySimpleValue1
MySimpleValue2


In Perl: Just type "print "$MySimpleArray[0] $MySimpleArray[1] $MySimpleArray[2]\n";" - Note that the $ character needs to precede the variable name when you want to get the individual value of an array element (printing @MySimpleArray would print out all elements) - The \n, indicating a carriage-return, line-feed or new-line isn't necessary, but is nice if you don't want your output on the same line as your next command prompt:

host # perl -e '@MySimpleArray[0] = MySimpleValue0; @MySimpleArray[1] = MySimpleValue1; @MySimpleArray[2] = MySimpleValue2;print "$MySimpleArray[0] $MySimpleArray[1] $MySimpleArray[2]\n";'
MySimpleValue0 MySimpleValue1 MySimpleValue2


In Awk: Just Type "print MySimpleArray[0],MySimpleArray[1],MySimpleArray[2]" - Note that the $ or @ symbol "must not" precede the variable name when you want to get the value. The comma in between the values ensures that a space will be printed between them for clarity's sake. Note that awk arrays need to be iterated over to be entirely printed out, and then extra care has to be taken if you want to get the variables out in the correct sequence (for another day) :

host # echo|awk '{MySimpleArray[0] = "MySimpleValue0"; MySimpleArray[1] = "MySimpleValue1"; MySimpleArray[2] = "MySimpleValue2";print MySimpleArray[0],MySimpleArray[1],MySimpleArray[2]}'
MySimpleValue0 MySimpleValue1 MySimpleValue2


In C: Just type "printf("%s\n", MySimpleArray);" to get the value for your character array. Note, again, that, for these posts, we're not going to get into the compilation part of creating a working C program:

host # ./c_program
MySimpleArray


And, now we've got two out of the three of the "basics" covered. In our next post on this subject, we'll take a look at the third most common variable/value type: The hash or associative array (which, as chance would have it, are technically what Awk arrays are :)

Best Wishes,

, Mike