Tugger the SLUGger!SLUG Mailing List Archives

[SLUG] bash tips (tr, cut, loops, fields, records) Was: shell scripting help

<quote who="Daniel Bush">

> Writing a little utility to help me on something but having trouble.
> Why does f stay blank?

Answer (which I think was mentioned in earlier responses): The parent shell
doesn't have access to the subshell's scope. The usual way of doing this is
to provide output from the loop into a variable, like this:

  PANTS=$(echo "foo|bar" | while ... echo -n $F ...)

Solution: Depends on the actual task rather than the example. :-)

> danb@lin4:test$ echo "foo|bar" | awk 'BEGIN{RS="|"}{ print $1 }' | while
> read s; do echo $s; f=$s; done; echo "'$f'"
> foo
> bar
> ''

A couple of thoughts (note that I always use caps for variables for

  echo "foo|bar" | tr '|' '\n' | while read S

tr is awesome.

Then, assuming the number of fields in each record is consistent (and in a
real example you're probably in a loop of some kind over the records before
you're in a loop over the fields):

  echo "foo|bar" | tr '|' '\n' | while read S; do
    echo $S # or otherwise do processing with each field
  F=$(echo "foo|bar" | cut -d'|' -f2)

cut is awesome.

Another way of looking at records/fields, if that is the problem you're
actually facing (beyond the simplified example):

  while read RECORD; do
    echo $RECORD | tr '|' ' ' | while read FIRSTNAME LASTNAME; do
      echo "Welcome, Mr. $LASTNAME,"
  done < records.txt

(Instead of mucking around with tr to muck about with the record separator,
you could just use the bash IFS variable, but there are some little catches
with that, which are not worth going into for now.)


- Jeff

linux.conf.au 2010: Wellington, NZ                http://www.lca2010.org.nz/
   He'd never undressed a woman with his eyes. Perhaps army boots, school
                uniform, or a nightie, but never undressed.