Showing posts with label sed. Show all posts
Showing posts with label sed. Show all posts

Monday, August 18, 2008

Unix and Linux Online Dictionary Shell Script

Hey There,

Today's Linux/Unix bash shell script is is a blatant exploitation of a post we did, not too long ago, where we put together a Thesaurus shell script. This time we're creating a shell script to emulate a full-function dictionary. The actual online source we draw from (Dictionary.com) deserves the credit for knowing what virtually every word in the English language means ;)

A dictionary can, obviously, come in handy when you're reading a book. As to its application on Unix or Linux, the usefulness is debatable. I do find, from time to time, that I don't know what a word in a man page, or info file, means (although that word is usually not in the dictionary, anyway ;). At times like those, this script has the potential to come in pretty handy. I'm just lazy enough to script out direct access to an online dictionary rather than open my web browser ;)

Like our previous script, this script uses wget and sed. This script was also written using "brute force" scripting (that's my term for writing it, directly, as I think it). I'm sure it could be made more comprehensive and technically efficient, but it's such a short script, anyway, that I decided not to kill myself rethinking it (or removing duplicate "sed" statements ;). The output could use some massaging, too, but at least I've got it to the point where it's legible.

Below is a screen shot of the script's output. Your results may vary. I didn't really have the time to test every possible way this could go wrong (Thank God ;)

Click the picture below to see it in full size:

Dictionary Script Output

Below is a screen shot of the script's output when choosing a word with multiple returns:

Click the picture below to see it in full size:

Long Results

As a note of caution, be prepared for multiple screens worth of output. If you need to look up the meaning of a word like "work," you should probably pipe the command to "more", like:

host # ./dict.sh word|more

Hope you enjoy this script, and can find some use for it. Any suggestions for improvement would be greatly appreciated. You probably noticed, from the above screenshots, that, every once in a while, a definition will get skipped... so that's still on the to-do list ;)

Now, to tackle the online Encyclopedia :)

Cheers,


Creative Commons License


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

#!/bin/bash

# dict.sh - Know what you mean!
#
# 2008 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

if [ $# -lt 1 ]
then
echo "Usage: $0 YourDictionaryTerm"
echo "May be two or more words separated by spaces"
echo "but only one definition per execution."
echo "Ex: $0 phone"
echo "Ex: $0 phone number"
exit 1
fi

args="$@"
wget=/usr/bin/wget

if [ $# -gt 1 ]
then
args=`echo $args|sed 's/ /%20/g'`
fi

echo

$wget -nv -O - http://dictionary.reference.com/browse/"$args" 2>&1|egrep -v 'Share This|Amazon.com|Reference.com|Thesaurus.com|Jobs|Copyright|To learn more|Download Now|Buy the Book|Origin'|egrep -i 'adjective|noun|verb|luna-Ent:|No results found|go/| suggestions:'|sed -e 's/$/\n/' -e :a -e 's/<[^>]*>/ /g;/</N;//ba' -e 's/\&[A-Za-z]*\;/ /g' -e 's/ / /g' -e 's/\(.\)$/\1\n/' -e 's/Would you.*$//' -e 's/[^A-Za-z0-9\. \n]//g' -e 's/\([0-9]\.\)/\n\1/g' -e 's/^.*Pronunciation//g'

exit 0


, Mike




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

Wednesday, July 30, 2008

The Thesaurus Shell Script - New And Improved!

Hey There,

Today's post is a follow up on a post we did just last week on creating an online Thesaurus using shell scripting. In it, we took an already existing Thesaurus script called thes.sh from gentoo.org and spiffed it up a little so that you could use multiple word queries and extract the suggestions the online Thesaurus would give you if it couldn't find a match for your word or phrase. Of course, sometimes it couldn't find a match for you and, also, had no suggestions... You can't win 'em all ;)

Thanks for this post's updated, and more platform-independent, script goes out to Fred Stephens (who's starting his own Linux revolution over at Linux Latitude) and (like so many other folks who, sometimes, prefer to remain nameless) his help in modifying this script so that it would also run correctly on a few more Linux and Unix distro's I didn't have access to, is greatly appreciated!

In an effort to make the script more portable as well, we used wget instead of lynx and took away the dependency on the html2text program by replacing that versatile (but not always available) software with a series of simple sed executions. This, of course, didn't work exactly the same (or "the same enough" ) on as many distro's as possible. Of course, I knew, when I wrote it, that I couldn't possibly test it on every available platform, so the possibility of it behaving differently on someone else's OS was always there (I think it always is and always will be). But, especially as time lumbers on, if we let hurdles like that slow us down, we'll all eventually accomplish less and less in direct opposite proportion to the amount of variety the computing industry offers us (which is growing more and more abundant as I type). Eventually, no one would ever write any sort of program, spark an original thought or attempt to improve and/or modify solutions unless they had a blank check from the government (or a giant conglomerate) to fund their every notion ;)

But that's one of the great things about the internet. Although I'll agree that (to a certain extent) it promotes seclusion and separation of physical entities from the "uncomfortable" prospect of having to physically interact with one another, the flipside of that coin is that the internet provides the world's largest forum for the free interchange and exchange of information and ideas and makes it possible for like-minded individuals to pool their efforts and ingenuity to produce more, and better, solutions to problems at a much snappier pace.

This rewrite addresses an issue with the one part of the script I just "knew" in my gut wouldn't port to some distro somewhere: the sed execution line. As I mentioned above, the free (licensed under the GPL) software html2text is a project that's had a lot of development hours put into it (actual releases and versions, etc ;), so it's obviously much much better at parsing out html and converting it to plain text than any series of sed commands I could ever string together on a given afternoon. Again, we chose to use sed in order to try and make this script accessible to users who couldn't get their hands on html2text (which also requires python), since sed comes standard on every Linux and Unix distro I know of (and has been around for a long time).

In any event, the script's been spruced up a bit and should run cleaner (The change isn't drastic, but it's definitely significant. If you noticed any garbage characters getting returned to you when you ran the original, this rewrite should, hopefully, fix that for you :)

Thanks, again, for your contribution, Fred :)

BTW, if you want to see sample output, there's a picture on the parent post about this Thesaurus shell script. I'm not jamming it in here again to try and keep this blog light (although, I see I've typed another novel already ;)

Cheers,


Creative Commons License


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

#!/bin/bash
# Thesaurus - Find something original to say :)
# 2008 - Mike Golvach - eggi@comcast.net (modified slightly by Fred J. Stephens - fjs205@gmail.com)
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#
if [ $# -lt 1 ]
then
echo "Usage: $0 YourThesaurusTerm"
echo "May be two or more words separated by spaces"
echo "but only one definition per execution."
echo "Ex: $0 leader"
echo "Ex: $0 big name"
exit 1
fi
args="$@"
wget=/usr/bin/wget
if [ $# -gt 1 ]
then
args=`echo $args|sed 's/ /%20/g'`
fi
echo
$wget -nv -O - http://thesaurus.reference.com/search?q="$args" 2>&1|\
egrep -i 'Synonyms:|Definition:|No results found|Thesaurus suggestions:'|\
sed -e 's/<br \/>/\n/g' -e 's/<[^>]*>//g' -e 's/ / /g' -e 's/\(.\)$/\1\n/' -e 's/Would you.*$//' -e 's/\ / /g'

exit 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, July 7, 2008

Variable MultiLine Spacing With Sed On Linux Or Unix

Hey There,

Today's post is going to be on a relatively basic subject that can elude a lot of folks who use sed casually. I, myself, for years, only used it to print out matched patterns or do pattern substitutions, but it's capable of much more than that. I don't think it's quite up there with awk (insofar as the programming functionality goes), but it does have lots of neat features (like letting you switch between the current and hold buffer, for example) that can sometimes make it the preferred tool for the job. Especially if you're like me and you're not attached to any one language or interpreter. My basic philosophy is: Whatever can get it done the fastest and most efficiently. I think it works nicely, as philosophies go, since I also compulsively automate everything ;)

For this post, we'll focus on "line spacing" (If anyone calls it something else, I'm referring to the number of spaces between lines). This is one thing that sed can do relatively simply and which is requested quite often from end users. The following tips should work for both Unix and Gnu/Linux sed.

The great thing about this feature is that it's so easy to use that, if you haven't used it already, you'll be amazed at the simplicity :)

Say, for instance, you had a file named FILE with the contents:

abcdef
ghijkl


this is all you would have to do with sed to make it double-spaced (Note that I'm leaving the output redirection to another file, since it's not really germane to the explanation and you probably already know how to redirect the output of one process to another. And, since this blog is for users of all skill levels, check out any of these old posts on using sed in a wide variety of situations if you don't. See below for more information on this feature:

host # sed G FILE
abcdef

ghijkl

# host


Pretty simple, yeah? :) The "G" argument to sed simply appends whatever follows it to the pattern space that gets printed out. Since we didn't have anything to print out, it prints a space by default.

Now, if you want to triple space, it's just a little more complicated, but not much. Here's how you'd do that

host # sed 'G;G' FILE
abcdef


ghijkl


#host


Note that we had to put the arguments in single quotes, since there are (of course) more than one ;) We could have written the last command as:

host # sed 'G' FILE

and gotten the same result as without the quotes, since there was only one argument to sed. If you want to quadruple-space, just use 3 G's, etc. That's about as simple as it gets on a single command line without control characters :)

It's also interesting to note (and overlooked in this old post on using Perl like sed) that you can use "r" and "w" to read from, and write to, files so you don't need to do any redirection outside of your one-liner.

For instance, if you wanted to read information in from another file (FILE2 with contents "xyz") and double space, you could type:

host # sed 'G;r FILE2' <FILE
abcdef

xyz
ghijkl

xyz
host #


Not exactly the same, but pretty useful in different situations.

Also, you can write out to a file, using w, so you don't have to do output redirection after-the-fact, like this (we'll overwrite the FILE2 file with the contents of FILE):

host # sed 'G;w FILE2' <FILE
abcdef

ghijkl

host # cat FILE2
abcdef

ghijkl

host #


Hope you enjoyed today's post and it gets you a little more interested in sed. We'll be looking at in the future, of course, as there are a lot more things you can do with it (especially if you escape the command-line construct)

Cheers,


, 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

Thursday, March 27, 2008

Manual Mass File Patching On Linux Or Unix

Good Day Good People :)

In previous posts we've looked at various aspects of the diff command, including augmenting it to generate unique content only and work with users, groups and permissions.

Today, I thought we'd look at diff's usage in a, generally, manual process and peek at the first step toward automation. Everything in this post can be scripted out to provide more granular control, and done much more easily. I thought doing it in a laborious tutorial style to start out with would be best to get the major parts of the process laid out simply and, hopefully, written in such a way that they're simply understood. After reading that last sentence, I'm wishing myself lots of luck ;)

For purposes of our example today, we're going to assume that we have a directory in which we keep 3 executable files. All of these files are approximately the same, because they all do approximately the same thing, just for different programs. For simplicity, they've been named: file1, file2 and file3, as shown in this directory listing:

host # ls
. .. file1 file2 file3


All of their contents are also almost totally identical:

host # cat file1 file2 file3
#!/bin/bash
# Start File1 Process

COMMAND_ARGS="-d --takeforeverandaday"

HOMEDIR="/usr/binky"

#!/bin/bash
# Start File2 Process

COMMAND_ARGS="-d --takeforeverandaday"

HOMEDIR="/usr/binky"

#!/bin/bash
# Start File3 Process

COMMAND_ARGS="-d --takeforeverandaday"

HOMEDIR="/usr/binky"


For today (and this would work if we had 5000 files, but this post is going to be long enough ;) all we need to do is change the HOMEDIR standard variable in all of our scripts to BASEDIR. I'm not exactly sure why. Someone with more authority than me or you decided it would be a good idea. They will probably change their mind and have us switch it back next week ;)

The first thing we should do is create a backup directory and do our work there.

host # mkdir ../u
host # cp file* ../u
host # cd ../u
host # ls
. .. file1 file2 file3


Then we'll just use a simple while loop and feed each file to sed and make the substitution, which we'll dump into another file called FILENAME.diff (So, file1 will get the substitution made on it by sed, and that difference will be put into a new file called file1.diff). Within that same loop, we'll be using the actual command "diff -e" to create an "ed" (A very basic Unix and Linux editor) patch file. Note that, for file1, this new file will be called file1.patch and that we echo a "w" and a "q" (on separate lines on purpose) into the bottom of the patch file.

host # ls -1d *|while read x;do sed s'/HOMEDIR=\"\(\/usr\/binky\)\"/BASEDIR=\"\1\"/' $x >$x.diff;diff -e $x $x.diff >$x.patch;echo w >>$x.patch;echo q >>$x.patch;done


We could have deleted our file*.diff files above, as well, but I thought you might like to take a look at them. These serve as proof that our sed command actually worked :) HOMEDIR is now BASEDIR!

host # cat file1.diff file2.diff file3.diff
#!/bin/bash
# Start File1 Process

COMMAND_ARGS="-d --takeforeverandaday"

BASEDIR="/usr/binky"

#!/bin/bash
# Start File2 Process

COMMAND_ARGS="-d --takeforeverandaday"

BASEDIR="/usr/binky"

#!/bin/bash
# Start File3 Process

COMMAND_ARGS="-d --takeforeverandaday"

BASEDIR="/usr/binky"


Now, let's delete the *.diff files and take a look at the patch files. These are all considered "ed" scripts. This means that we can feed them to the "ed" Linux/Unix editor and have it execute commands for us automatically. This will come in handy in a second :)

host # rm *.diff
host # cat file1.patch file2.patch file3.patch
5c <--- These first three
BASEDIR="/usr/binky" <--- lines were created
. <--- by "diff -e"
w <--- We manually added
q <--- these last two!
5c
BASEDIR="/usr/binky"
.
w
q
5c
BASEDIR="/usr/binky"
.
w
q


The next step in the process is to apply those patches. We're going to be doing this all in our test directory, so there's no need to tar up all the patch files for a move to our "live" script directory

host # ls
. file1 file2 file3
.. file1.patch file2.patch file3.patch


So, now we're ready to test our mass change and pray all goes well. Note that, since we're still in our backup directory, we can do lots of damage to the scripts in here and it shouldn't make a difference to anyone. Only we will have to live with the shame ;)

Now, we'll do another fancy command line and pipe the output of "ls -1d *", grepping out all the patch files and then using "ed" to patch each file in the directory. Notice that the syntax for patching a file with an "ed" diff script is "ed FILENAME <FILENAME.patch" - This would normally hang and wait for us to send it a control-D or some other signal, but, since we echoed the "w" and "q" characters into the patch files, "ed" knows to write (w) and quit (q) - At the end of the command pipe, we'll purposefully not delete all the patch files. You can remove them if you like, but we'll be looking at using them to undo changes in a future post!

host # ls -1d *|grep -v patch|while read x;do ed $x <$x.patch;done
107
107
107
107
107
107
host # ls
. file1 file2 file3
.. file1.patch file2.patch file3.patch


Okay, we're all done and now we can check the results. Looks like everything in our (potentially huge amount of) files got patched appropriately :) This shouldn't be a surprise since we checked our sed output already, but you never know.

host # cat file1 file2 file3

#!/bin/bash
# Start File1 Process

COMMAND_ARGS="-d --takeforeverandaday"

BASEDIR="/usr/binky"

#!/bin/bash
# Start File2 Process

COMMAND_ARGS="-d --takeforeverandaday"

BASEDIR="/usr/binky"

#!/bin/bash
# Start File3 Process

COMMAND_ARGS="-d --takeforeverandaday"

BASEDIR="/usr/binky"


In a future post we'll look at a script that will allow us to do what we've just done today and make life a little easier when doing mass updates or patching :)

Cheers,

, Mike




Thursday, March 20, 2008

Generating Only Unique Content From Two Somewhat Similar Files

Hey There,

I see this, in one variation or another, on the message boards from time to time. So, touching back on our earlier post regarding making our own diff to deal with directory permissions, today we're going to look at a script that performs another function not built in to the standard "diff" command on Linux or Unix, and fairly simply implemented in ksh or bash.

Our script today, takes the input of two files (generally text files) of different sizes; however, they can be of equal size. It doesn't seem to make a difference ;) The only restriction on the usage of the script we're presenting today is that, assuming both files are of unequal size, the smaller of the two files should be listed as the primary argument to the script (we'll call it "rdiff") and the larger file should be the secondary argument, like so:

host # ./rdiff smallfile largefile

and, of course, if they're of equal size:

host # ./rdiff file file

The output of the script will be a file named "Unique.out.smallfile.largefile" with "smallfile" and "largefile" being the values of the file names passed to the script on the command line.

Basically, our script uses sed and grep to determine if lines in the smaller file are duplicated in the larger file. If those lines are duplicated, they are then removed from the final output, so that your "unique" output file only includes lines that existed exclusively in the small and large file. All duplicate information is removed.

Enjoy and cheers,


Creative Commons License


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

#/bin/ksh

#
# rdiff - find unique content in two files
#
# 2008 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

if [ $# -ne 2 ]
then
echo "Usage: $0 SmallFile LargeFile"
exit
fi

FileA=$1
FileB=$2

cp $FileB ${FileB}.old

for x in `<$FileA`
do
grep ^${x}$ $FileB >/dev/null 2>&1
if [ $? -eq 0 ]
then
echo $x >>tmpfile
fi
done

for x in `<tmpfile`
do
sed "/^$x$/d" $FileB >>newtmpfile
mv newtmpfile Unique.out.${FileB}.${FileA}
done

rm tmpfile


, Mike




Wednesday, February 27, 2008

Simplifying File Renaming Using Bash Without Sed

Hello again,

This is a little tip I picked up that I really like. It's not new; just something I never gave any real thought to. It has to do with renaming files (A common enough task) en masse and how to do that in as few keystrokes as possible. But that really puts a limitation on this trick that doesn't exist. It can be used for many other purposes.

I was in the bad habit (Well, it's not a bad habit, really, since it'll work on almost any distro of Linux or Unix) of typing extremely long command lines to change file names. For instance, if I had a directory full of script files that looked like this:

host # ls
script1 script2 script3


and I wanted to copy them all off to files with a .bak extension (In case I screwed up my edits on the originals), I would almost always type something like the following (Note that this command line is a perfectly acceptable way to rename your files if you can't do it the way I'm going to explain here):

host # ls -1 script*|while read name;do newname=`echo $name|sed 's/$/\.bak/'`;cp $name $newname;done

which would work perfectly well, and leave me with:

host #
script1 script1.bak script2 script2.bak script3 script3.bak


In Bash (on Linux or Unix) you can get around this with variable expansion. Like I said, especially in this instance, this may not seem like much, but it does save a lot of typing (and can be used to help you save time in a lot of different ways if you use your imagination :)

So, for purposes of demonstration, we'll put everything back the way it was:

host # rm *.bak
host # ls
script1 script2 script3


Now we're going to look at Bash's expansion operators and see how much easier they can make this whole process. The expansion operators are, basically, curly brackets - which can be nested - containing values. The two most important things to note about them are that:

1. The values must be separated by commas (e.g. {1,2,3})
2. The values can't contain any spaces between themselves and the commas - on either side - unless the values are quoted, like so (there can also be no space between the quotation marks and the comma separators):

Correct = {"1 "," 2 "," 3"}
Who Knows? = {1 , 2 , "3"}


So, now we can do the exact same thing we did above (add the .bak extension to our 3 script files), but do it a lot more cleanly and quickly - not to mention the fact that your input shouldn't bleed over a simple 80 column tty display any more ;)

host # ls -1 script*|while read name;do cp $name{,.bak};done
host # ls
script1 script1.bak script2 script2.bak script3 script3.bak


Here's an even shorter line, but it might cause you problems, given "for x"'s default behavior of reading each variable on a line as the value of x. This wouldn't work very well if you were trying to operate on files with spaces in their names (You can read more on that in our previous post on working with Windows generated file names):

host # for x in `ls -1 script*`;do cp $name{,.bak};done

Not only do Bash's built in variable expansion operators shorten my line, once you get used to using them they make it more easily readable. If you noted that my variable expansion, inside the curly brackets, was missing a value before the first comma, that was intentional. Although you can't have spaces between the values in your expansion set, you can have an empty value (no spaces). This way the first "append" that the variable expansion does is just like doing no append at all.

For example:

host # ls script{1,2}
script1 script2


And now, with a blank first variable (You can put your blank variable anywhere - more than once - but it makes the most sense to use it first in the "cp" command above since I want to copy from the original file name to the new name):

host # ls script{,2}
ls: script: No such file or directory
script2


Like I said, this little trick (well, technically not a trick, since it's built in to Bash ;) has saved me a lot of time and I hope you find it useful as well!

Cheers,

, Mike




Monday, January 7, 2008

Sed Manpage Markup Language Translation Script

As I note in the header of this script it's somewhat imperfect. In fact, for the most part it may be almost completely obviated by the last few years of advancements in OS translation of the manpage itself. It is, however, another example of just how crazy you can get with sed.

Back in the day (and I still see this from time to time on some current Unix and Linux systems), if you redirected the output of "man whatever" to a file, like so, in order to get the manpage without using sed, or some other information-massager:

man whatever > OUTPUTFILE

you'd end up with a script full of garbage. Not that it was completely unreadable, but you'd have to filter out all the markup language graffiti on your own (in your head, if possible ;)

That's what prompted me to begin work on stripping down a garbage-output manpage to a simple, and easily readable, file using sed. You may notice, if you need to do this kind of translation and use this method, that a few markup language remnants remain. Feel free to embellish this work to remove them as well. The final section of the script is the easiest place in which to do this. Which also answers the question: Why so many individual replacements and not just one compact regular expression? As noted above, this is a work in progress that I'm trying to make work for a lot of different flavors (and versions) of Linux and Unix. Once I feel that I've run down every possible marker, I'll make it a lot tidier and wrap it up with a bow ;)

Enjoy,


Creative Commons License


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

#!/bin/sh
#
# Semi-Imperfect Man-Source To Regular-File Translator
# 2008 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

echo >> $1.txt

sed -e '1,/NAME/d' -e '/^\.\\"/d' -e 's/^\.if//' -e '/^\.TH/d' -e '/^\.de/d' -e '/^\.ds/d' -e '/^\.ll/d' -e '/^\.in/d' -e '/^\.ti/d' -e '/^\.ie/d' -e '/^\.br/d' -e '/^\.el/d' -e 's/^\.\.//' -e 's/^\.SH\(.*\)/\1\
/' -e '/^\.nr/d' -e '/^\\f/d' -e '/^\.}f/d' -e '/SYNOPSIS/i\
' -e '/COPYRIGHT/i\
' -e '/DESCRIPTION/i\
' -e '/SEE ALSO/i\
' -e 's/\.PP//' -e '/^\.PD/d' -e 's/^\.BR//' -e '/^\.BI \\/{
N
s/\.BI \\/ /g
s/\n/ /g
}' -e '/^\.B \\/{
N
s/\.B \\/ /g
s/\n/ /g
}' -e '/^\.B/{
N
s/\.B/ /g
s/\n/ /g
}' -e '/^\.IR/{
N
s/\.IR//g
s/\n/ /g
}' -e 's/\.SB//' -e '/\.TS/d' -e '/\.TE/d' -e 's/^\.IX//' -e '/\.LP/d' -e 's/\.TP *[0123456789]*//g' -e 's/\\fB//g' -e 's/\\fR//g' -e 's/\\fP//g' -e 's/\\fI//g' -e 's/\\| *//g' -e 's/ n //g' -e 's/ t //g' -e 's/\\^ *//g' -e 's/\\//g' -e 's/\.FN//g' -e 's/\.I//g' -e '/^\.SM/d' -e 's/^\.RS//' -e 's/^\.RE//' -e 's/\.SS//g' $1 >> $1.txt


, Mike




Friday, January 4, 2008

Getting Rid Of HTML Tags And Leaving The Comments

Hey there,

If you've ever found yourself stuck in a spot where you needed to convert an html page to straight up text (for whatever reason), today's script might be a nice addition to your tool-kit. It's been tested in ash and bash on Linux and on sh, ksh and bash for Solaris.

The main reason I wrote this script was to break down html pages (at the code level) by removing all the html tags, while leaving all the comments. I primarily prefer to do this, when I can, in the shell rather than cut-and-paste from Firefox or Internet Explorer since the cut-and-paste method has a nasty habit of removing all formatting. Well, that's not entirely true. The carriage returns do usually manage to make it through unscathed ;)

This shell script is basically a wrapper for a few sed commands. While most readers are probably somewhat familiar with sed and how to use it, I find that a lot of folks on the forums request help when it comes to using some of its more advanced functionality, like matching patterns across multiple lines. This script matches (and removes) any tags that begin with the "<" character and end with the ">" character. I use it for html, but it could easily be used (without any porting at all) on any markup language file that uses the same tagging convention.

For clarity, I split up the single-line match from the multi-line match. You'll note that the second invocation of sed is where we write our expression to work on a html tag-pair that spans any number of lines greater than one. We'll go into that more in a future post, but for now, note that we basically find all opening "<" characters that don't have an ending ">" character on the same line, and consume everything on every line all the way up to, and including, the ending ">" character. The simplest solution, once we've determined that we're going to traverse multiple lines, is to replace all newlines ("\n") with spaces. So, basically, when we do the multi-line match, we're converting that multi-line entry into a single line so that the match can be made. As I said, this subject can be a little too convoluted to go into too much detail for the purposes of this post ;)

I've called this script htstrip (call it whatever you like) and you can invoke it like this:

host # ./htstrip filea fileb filec <-- Doesn't matter what the file names are; they don't have to be .htm files, etc.

And, as an example. This is the type of output you could expect to see:

host # cat filea.htm
<a> bob1 </a>
<a> bob2
</a>
<a> bob3
bob4
</a>
<!-- this is
a comment
-->
<a> bob5
bob6
bob7
</a>
host # ./htstrip filea.htm
host # cat filea.htm
<-- Note that our original file is saved as filea.htm.old, just in case
bob1
bob2
bob3
bob4
<!-- this is
a comment
-->
bob5
bob6
bob7


Note, that, as I mentioned in the title, I've purposefully made it so that standard html comments will remain. If you don't want these in your output either, a small modification to the script can make sure those go away too. Note also that we use shorthand in the "for x" loop. This post has nothing to do with that, but it's nice to know that you don't need to write "for x in BLAH" if you're using the default input. Technically, it's a better idea to use the full form. Especially if you're writing a huge script or are dealing with issues of scope, etc. ...For another day.

Hope this helps you out :)


Creative Commons License


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

#!/bin/sh

#
# htstrip - 2008 - Mike Golvach - eggi@comcast.net
#
# Usage: htstrip filea fileb filen
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License;
#

trap 'rm -f temp temp2 temp3;exit 1' 1 2 3 9 15

if [ $# -lt 1 ]
then
echo "htstrip needs to know what files you want to strip!"
exit 1
fi
for x
do
sed -e 's/<[^>]*>//g' $x >> temp
sed -e '/<[^>]*$/{
$!N
/^[^>]*>/{
s/\n/ /
s/<[^>]*>//g
}
}' temp >> temp2
sed -e '/^ *$/d' temp2 >> temp3
rm temp temp2
mv $x ${x}.old
mv temp3 $x
done


, Mike




Tuesday, November 27, 2007

Using find and xargs to locate Windows Files

A lot of times, when you're asked to find something on a machine, and you only have a moderate idea of what you're specifically looking for, you'll use the obvious command: find. find is a great command to use because you can use wildcards in your expression argument. So, if you know that you're looking for something like "theWordiestScriptEver," and you have no idea where it's located on your box, you could find it by typing just this:

find / -iname "*word*" -print

This will find every file on the system (even on non-local mounts if you have them set up) and only print the results for files with the word "word" in the name. Note that the "-iname" option matches without regards to case, so h and H both match. This option isn't available in all versions of find. If you don't have this option available to you, you'll get an error when you run the above line (just use "-name" instead). The standard Solaris find does not do "case insensitive" pattern matching, so your best bet is to find the smallest substring that you're sure of the case on, or use another attribute to search for the file (like -user for the userid or -atime for the last access time). Alternatively, you could spend hours stringing together a bunch of "or" conditions for every conceivable combination of upper and lower case letters in your expression.

Now suppose you needed to perform an action on a file you found. You could use find,s built-in exec function, like so:

find / -iname "*word*" -print -exec grep spider {} \;

This will perform the command "grep spider" on all files that match the expression. Which brings us around to the next predicament. What do you do if you have to try and find something simple, have no idea where it is on your box "and" that box hosts file systems that Windows users are allowed to write files to. The above example should work just fine on those. My own advice is, if you can get away with just using find, do so, since it handles all of the rogue characters, tabs and spaces in Windows files on its own.

Now, if you have to do something much more complicated (or convoluted), you'll want to pipe to a program like xargs, which is where all those funny Windows file names and characters (some of which are special to your shell) start to cause issues. Again, this would return ok:

# find . -name "*word*" -print
./word - file's
./word file
./word & file's
./word file's


But this will become an issue if you pipe it to xargs, as shown below:

# find . -name "*word*" -print|xargs ls
xargs: Missing quote: files


Ouch! xargs doesn't deal with those spaces, tabs and special characters very well. You can fix the space/tab problem very simply by using xarg's "named variable" option. Normally, xargs acts on the input it receives (thus: "xargs ls," above, is processing ls on each file name find sends it), but you can alter how it deals with that data in a simple way (at least as far as the spacing issue is concerned). Example below:

# find . -name "*file" -print|xargs -ivar ls "var"
./word file
# find . -name "*word*" -print|xargs -ivar ls "var"
xargs: Missing quote: ./word - files


But, in the second invocation above, you see that it still can't handle the "shell special" characters, like "'" or """ <--- Double quote - so it's time to step it up. I prefer to just sanitize everything that's not kosher, even though I know I don't technically have to avoid the ---> \ / : * ? "< > <--- characters, since Windows won't allow them as parts of file names. It seems easier just to react on anything that isn't a letter or number and pass it along with enough escapes (back slashes) so that xargs can parse it correctly, and get you back good information. Here's how to do that; using sed (and a little grep, to keep it neat), also:

# find . -name "*word*" 2>&1|grep -iv denied|sed "s/\([^A-Za-z0-9]\)/\\\\\1/g"|xargs -ivar ls "var"
./word - file's
./word file
./word & file's
./word file's


And now you can use find, combined with xargs, on all the files you have permission to see, no matter what goofy characters are in them :)

, Mike





Sunday, November 11, 2007

Editing Startup Scripts on Solaris - Part 3 - The VI Way

As we mentioned earlier, using Sed, Awk or command line Perl to edit your source startup files in /etc/init.d is a perfectly acceptable practice. However, because of Solaris' tendency to use hard links in their "run level" directories, this can cause problems, as using these utilities changes the "inode number" of the source file and separates it from the "run level" script.

The answer is to do the simplest thing. Edit all the source files using an editor, like vi. If you edit them in this way, after your changes have been made and you've saved your edits, the inode number will be the same. The reason this usually isn't considered an option is that, if you have to comment out a large number of scripts, using vi can be very time consuming and can put you in a position to make a single error, or multiple errors, in some of your source scripts, since you'd have to repeat the same editing actions over and over again.

Here's a little piece of script that can make it so you can use vi to comment out your scripts (preserving the inode number) and not have to worry about making a hard-to-find error somewhere along the way. This way, like with Sed, Awk or command line Perl, you'll either do everything right or make the same mistake in all files ;)

This example uses the "here document" (referred to in this blog, in a previous post here) and inserting actual control characters (referred to in a separate earlier post here). For our purposes, since this script doesn't translate well into simple text, we'll use a basic legend:

[ctl-v] will mean hit the "control" and "v" keys at the same time.
[esc] will mean literally hitting the "escape" key.
[cr] will mean literally hitting the "return," or "enter," key.

And here it is - The script takes the arguments of any number of files that you want to totally comment out; placing "#" characters in the first position on every line.

#!/bin/sh

for x in $@
do
/usr/bin/vi $x <<-END
[ctl-v][esc]:g/^/s//#/[ctl-v][cr]][ctl-v][esc]:wq![ctl-v][cr]
END
done


Now you can run "Yourscript filea fileb filen..." and you will actually be doing real editing with vi,completely hands-off :)

P.S. If you don't want to see the vi output, and you're satisfied that the script is working as expected, just change the following line

from: /usr/bin/vi $x <<- END
to: /usr/bin/vi $x <<- END >/dev/null

, Mike





Saturday, November 10, 2007

Editing Startup Scripts on Solaris - Part 2 - The Rub

As we mentioned yesterday, it's generally best practice to edit, or update, your init scripts by editing the source file in /etc/init.d, rather than the link to it in one of the "run level" directories, like /etc/rc2.d

Given a specific example (For instance: we need to comment out 8 or 9 scripts in /etc/init.d) that we want to do fast, we've decided that just adding "#" symbols to the beginning of every line of all 9 scripts in /etc/init.d would be the fastest way.

We have a few options, like using Sed, Awk or command-line Perl, to take care of the work for us lickety-split. However these solutions, and others like them, present a general problem. There's nothing wrong with using these methods, in general, except that Solaris, right out-of-the-box, uses a lot of "hard links" in its "run level" directories to point back to the source script in /etc/init.d.

Hard links differ from the symbolic links we discussed yesterday in that they are not just "pointers" to the source file; they are actually links to the inode that the source file uses. In essence, they are another version of the exact same file, or, in different terms, another reference to the same file.

To illustrate the difference another way: If you delete a source file, the symbolic link to it will still exist, but if you try to edit that symlink, you'll be editing an empty file, since it's just a pointer to something that doesn't exist anymore. If you delete the source file and go to edit the hard link, you will still be able to edit the original file since the hard link points to the inode (not the filename) and removing the source file has just decreased the reference count of the inode.

When a hard link to a file is created, in essence, two copies of the file now exist. This presents an issue if you use Sed, Awk or command line Perl, because when you edit the source file in /etc/init.d using these methods, you're copying the changes to another file and then writing that back over the original: Changing the inode number! Now your source file and your file in the "run level" directory both point to different inodes, and updating the source file won't change the contents of the "run level" file.

There is an easy way around this. You can edit each of the 9 files using an editor like vi. But how to do it as quickly and easily as with Sed, Awk or command line Perl?

Tomorrow, we'll create a script that will do just that. It will edit your files for you, hands-off, and not change the inode number; thus ensuring that all of your changes will remain consistent in the "run level" directories, no matter what kind of links (soft or hard) they harbour.

Have a good Saturday Night :)

, Mike





Monday, November 5, 2007

The Advantage of Using Perl Like Sed or Awk

Hey There,

Mostly, in shell scripts, you won't want to call Perl to do any processing for you. If your script has gotten to the point of complexity that only Perl can do the job, you should probably be writing your script in Perl.

However, there are times when it makes sense to use it, if only for brevity's sake. Perl will, of course, impose a slightly heavier load on your system when you call it from the shell. But unless you've got a 3,000,000 line gutbuster of a script on your hands, you'll never notice the difference and the shell probably won't flag at all either.

One of the best ways to utilize Perl within a shell script is to mimic the functionality of Sed and/or Awk; insofar as they're used to perform simple find-and-replace procedures on a file.

The problem with Sed and/or Awk is that (and I know this is trifling) when you process a file with either, you've got to direct the output somewhere (possibly a temporary file) and then write that result back over the original file (possibly altering the original file's permissions, which would need to be reset. With Perl, you can avoid that last step and, possibly, make your script more readable.

For instance: From within a shell script, this is what you'd have to do with Sed to replace the first instance of "bob" with "joe" for all lines in your file (we're assuming it has permissions of 755 and your system umask of 022 will make the new file have 644 permissions when it gets created).

sed 's/bob/joe/' filename >>tmpfilename
cp tmpfilename filename
chmod 755 filename


It's a slightly different command in Awk, but the copy-back and chmod still need to be done manually. If you call Perl, it will take care of managing that copy-back for you (by doing an inline edit which is - technically - the same thing at the execution level), like this:

perl -p -i -e 's/bob/joe/' filename

That's it. No worries about writing out to a temporary file and copying back. Now you don't have to worry about that and, as an added bonus, it looks a lot neater.

Simple as pie :)

, Mike