MCWong
Blah! MCWong

20040709 Friday July 09, 2004

ksh scripting #3: list elements

It seem unavoidable, at some point there is always some kind of list that needs spliting.


#
#  pl - print list elements delimited by '|'
#
function pl {
  l="$*|"

  while [ "$l" ]
  do
    e="${l%%\|*}"
    l="${l#*\|}"
    echo "$e"
  done
}

Here's to give it a go:


$ head -1 /etc/passwd | sed 's/:/|/g'     
root|x|0|1|Super-User|/|/bin/ksh
$ 
$ pl `head -1 /etc/passwd | sed 's/:/|/g'`
root
x
0
1
Super-User
/
/bin/ksh
$ 

Why '|' as separator? Well, when was the last time you see this '|' thing in the English language? And, when was the last time you process a bunch of shell command pipelines all concatenated together into a list to be processed? I supposed you get them more often with each pipeline on a separate line, as in a shell script (?!); which you could readily process with read, grep, awk, sed and a zillion other utilities.

Why not ':' as in /etc/passwd? I have scripts that process list of URL's, so 'http://...'! Not very convenient isn't it.

ksh scripting flashback: #1 #2

(2004-07-09 00:00:03.0) Permalink Comments [1]

Comments:

[Trackback] Interesting scripts, but I have another solution to the splitting problem using IFS. I offer the following, which should work in vanilla bourne shell, with the using the same delimeters as Man-Ching used. pl.sh #!/bin/sh line="$@" ...

Posted by Alan Hargreaves' Weblog on July 09, 2004 at 01:44 AM PDT #

Post a Comment:

Comments are closed for this entry.

archives
links
referers