Mailinglist Archive: opensuse (2430 mails)

< Previous Next >
Re: [opensuse] BASH - brain teaser, can it be done without a pipe?
  • From: David Bolt <bcrafhfr@xxxxxxxxxx>
  • Date: Sat, 19 Apr 2008 11:56:58 +0100
  • Message-id: <yqV+xFB6$cCIFwu8@xxxxxxxxxxxxxxxxxxx>
On Sat, 19 Apr 2008, David C. Rankin wrote:-

04:17 trinity~/linux/scripts> tmax=0; while read a b t c; do t=$(echo
"$t" | sed -e 's/\.//'); if (( $t > $tmax )); then tmax="$t"; fi; done
< ./cputemp.log ; tmax=$(echo "$tmax" | sed -e 's/\([0-9][0-9]\)\([0-9]
\)/\1\.\2/'); echo "Max temp is: $tmax"

Well, I've unravelled it a bit

tmax=0
while read a a t a # no need to use different names for
dummy variables
do
t=${t//\./} # does a global character replace,
just like adding 'g' to the end of a 'sed' expression.
[ "${t}" -gt "${tmax}" ] && tmax="${t}" # no need for an if ... fi for this
done < ./cputemp.log
echo "Max temp is: ${tmax::$[${#tmax}-1]}.${tmax:$[${#tmax}-1]}"


And since you're in the mood for tips, here's a few more:

You can replace basename with

${variable##*/}

The ## means to strip off from the beginning of $variable the longest
part that matches the string after the ##. In this case, that's a
wildcard and a '/' so matches all characters upto the last '/'.


You can replace dirname with

${variable%/*}

The % means to strip off from the end of $variable the shortest part
that matches the string after '%'. In this case, that's a '/' and a
wildcard and so matches from the last 'l' to the end of the string.


You can use

${variable//[[:digit:]]/}

to check if what's supposed to be a number really is:

if [ -n "${variable//[[:digit:]]/}" ]
then
echo "There's non-numeric characters in ${variable}"
fi


If you're doing some processing of files found using find, as I do when
transcoding flash videos to AVIs, you can use something like:

find -type f -name "*.flv" | \
while read inpname
do
outname="${inpname%.flv}.avi" # strip off the .flv extender and add
.avi
outname="${dest_dir}/${outname##*/}" # now add the destination path and strip
off the source path
ffmpeg -i "${inpname}" ${ffmpeg_options} "${outname}" && \
mv "${inpname}"{,old} # if the conversion worked, rename the
source file so it doesn't get done again
done


Regards,
David Bolt

--
Team Acorn: http://www.distributed.net/ OGR-P2 @ ~100Mnodes RC5-72 @ ~15Mkeys
SUSE 10.1 32bit | openSUSE 10.2 32bit | openSUSE 10.3 32bit | openSUSE 11.0a1
SUSE 10.1 64bit | openSUSE 10.2 64bit | openSUSE 10.3 64bit
RISC OS 3.6 | TOS 4.02 | openSUSE 10.3 PPC | RISC OS 3.11
--
To unsubscribe, e-mail: opensuse+unsubscribe@xxxxxxxxxxxx
For additional commands, e-mail: opensuse+help@xxxxxxxxxxxx

< Previous Next >
References