Re: Better use of awk/sed?
Salve Håkedal wrote:
> I script a simple accounting system using the old Spreadsheet calculator
> program SC. The following (part of a) script is to be called with one or
> more of these filenames:
> $ script 1st_term.cln 2nd_term.cln 3rd_term.cln 4th_term.cln
>
> #!/bin/bash
> accounts='
> INNTEKTSKONTOER
> ~~~~~~~~~~~~~~~
> 11 Reparasjon/Varer
> 12 Nytt instrument
> 13 Utleie
> 16 Eksport
<snip>
> Diverse
> 51 Porto/Frakt
> 53 Bankgebyr
> 55 Utleggsprovisjon
> 57 Kontingenter
> 60 Diverse u/mva
> '
> echo "$accounts"
> read -p 'type account number > ' acc_nr
>
> echo "$(echo "$accounts"\
> | awk '/'$acc_nr'/ { print $2, $3, $4 }'\
> | sed 's/[ ]*$//') for $(echo $@\
> | sed 's/_term\.cln/,/g') term"\
> | sed 's/\(, \)\([1-6][a-z][a-z]*\), term/ and \2 term/'\
> | sed 's/, term/ term/'\
>
> _____________________
>
> This does exactly what I want it to do, but I'm shure the last 6 lines
> can be written much better! I want to use only bash / awk / sed.
Let's try to clean that up a bit to try to figure out what it does.
echo "
$(echo "$accounts" |
awk '/'$acc_nr'/ { print $2, $3, $4 }' |
sed 's/[ ]*$//') \
for $(echo $@ | sed 's/_term\.cln/,/g') term \
" |
sed 's/\(, \)\([1-6][a-z][a-z]*\), term/ and \2 term/' |
sed 's/, term/ term/'
Hmm. No, I still don't entirely get it. Let's simplify and correct it a bit:
account=$(echo "$accounts" |
awk -v acc_nr="$acc_nr" '$1==acc_nr{print $2, $3, $4}')
files=$(echo $@ | sed 's/_term\.cln/,/g')
echo "$account for $files term" |
sed -e 's/\(, \)\([1-6][a-z][a-z]*\), term/ and \2 term/ \
-e 's/, term/ term/'
That last sed is a puzzle. You seem to be inserting commas on the first
sed then taking them out again on the second one. I THINK what you want
is to take your list of input files, change the suffix to a comma and
add "and" between the final 2 files plus a terminating word "term". If
so, all you need is:
account=$(echo "$accounts" |
awk -v acc_nr="$acc_nr" '$1==acc_nr{print $2, $3, $4}')
files=$(echo "$@" |
awk '{$NF="and " $NF " term";gsub(/_term\.cln/,",")}1')
echo "$account for $files"
Untested. If it doesn't work, provide some details on what you're really
trying to do.
Ed.
|