Apple script-get cpu usage as integer value - osx-lion

In terminal we can use
top -l 2 -F -R | awk '/CPU usage/ && NR>5 {printf "%d", $7+0}'
to get the value of cpu usage how can i get the value as an integer in apple script?
i tried this
set usedSpace to (do shell script "top -l 2 -F -R | awk '/CPU usage/ && NR>5 {printf "%d", $7+0}'") as integer
and gor the error
Expected “,” but found unknown token
then tried like this
set usedSpace to (do shell script "top -l 2 -F -R | awk '/CPU usage/ && NR>5 '; printf $5}") as integer
and got an error like this
error "Can’t make \"CPU usage: 6.40% user, 5.41% sys, 88.17% idle }\"
into type integer." number -1700 from "CPU usage: 6.40% user, 5.41%
sys, 88.17% idle }" to integer
can anybody help me solve this?
Thanks in advance

Try:
set usedSpace to (do shell script "top -l 2 -F -R | awk '/CPU usage/ && NR>5 {printf \"%d\", $7+0}'") as integer
or
set usedSpace to (do shell script "top -l 2 -F -R | awk '/CPU usage/ && NR>5 '; printf $5}") as text

Related

Sh script to output unused interfaces on linux

I asked the dark side and here's what it printed.....
#!/bin/bash
for interface in $(ip addr show | awk '/^[0-9]+:/ {print $2}' | tr -d :)
do
if ! ip addr show $interface | awk '/inet / {print $2}' | grep -q . ; then
echo $interface
fi
done
I want to add n+ variable directly so the output will be the interfaces that is not used by the system,
Done
I have these two scripts, one for Linux and one for Mac, I hope they serve you because I have tested them on Linux Ubuntu and Mac.
on linux
#!/bin/bash
# This script will output unused interfaces on Linux
# Get list of all interfaces
interfaces=$(ifconfig -a | grep -o '^[^ ]*:' | tr -d :)
# Loop through each interface
for interface in $interfaces; do
# Check if interface is up
if [[ $(ifconfig $interface | grep -c 'UP') -eq 0 ]]; then
# Output interface name
echo "$interface is unused"
fi
done
on mac
#!/bin/bash
# Get list of all network interfaces
interfaces=$(networksetup -listallnetworkservices | tail -n +2)
# Loop through each interface
for interface in $interfaces; do
# Get the IP address of the interface
ip=$(ipconfig getifaddr "$interface")
# If the IP address is empty, the interface is unused
if [ -z "$ip" ]; then
echo "$interface is unused"
fi
done
#!/bin/bash
count=0
for interface in $(ip addr show | awk '/^[0-9]+:/ {print $2}' | tr -d :)
do
if ! ip addr show $interface | awk '/inet / {print $2}' | grep -q . ; then
free_interfaces[$count]=$interface
count=$((count + 1))
fi
done
case $count in
0)
echo "No usable interface found."
exit 1
;;
1)
DEFIF=${free_interfaces[0]}
echo "The interface $DEFIF will be used."
;;
*)
echo "Available interfaces to select: "
PS3="Press a number to select an interface to use (1-$count): "
select interface in "${free_interfaces[#]}"; do
DEFIF=$interface
break
done
echo "The interface $DEFIF will be used."
;;
esac

Bash or Python efficient substring matching and filtering

I have a set of filenames in a directory, some of which are likely to have identical substrings but not known in advance. This is a sorting exercise. I want to move the files with the maximum substring ordered letter match together in a subdirectory named with that number of letters and progress to the minimum match until no matches of 2 or more letters remain. Ignore extensions. Case insensitive. Ignore special characters.
Example.
AfricanElephant.jpg
elephant.jpg
grant.png
ant.png
el_gordo.tif
snowbell.png
Starting from maximum length matches to minimum length matches will result in:
./8/AfricanElephant.jpg and ./8/elephant.jpg
./3/grant.png and ./3/ant.png
./2/snowbell.png and ./2/el_gordo.tif
Completely lost on an efficient bash or python way to do what seems a complex sort.
I found some awk code which is almost there:
{
count=0
while ( match($0,/elephant/) ) {
count++
$0=substr($0,RSTART+1)
}
print count
}
where temp.txt contains a list of the files and is invoked as eg
awk -f test_match.awk temp.txt
Drawback is that a) this is hardwired to look for "elephant" as a string (I don't know how to make it take an input string (rather than file) and an input test string to count against, and
b) I really just want to call a bash function to do the sort as specified
If I had this I could wrap some bash script around this core awk to make it work.
function longest_common_substrings () {
shopt -s nocasematch
for file1 in * ; do for file in * ; do \
if [[ -f "$file1" ]]; then
if [[ -f "$file" ]]; then
base1=$(basename "$file" | cut -d. -f1)
base2=$(basename "$file1" | cut -d. -f1)
if [[ "$file" == "$file1" ]]; then
echo -n ""
else
echo -n "$file $file1 " ; $HOME/Scripts/longest_common_substring.sh "$base1" "$base2" | tr -d '\n' | wc -c | awk '{$1=$1;print}' ;
fi
fi
fi
done ;
done | sort -r -k3 | awk '{ print $1, $3 }' > /tmp/filesort_substring.txt
while IFS= read -r line; do \
file_to_move=$(echo "$line" | awk '{ print $1 }') ;
directory_to_move_to=$(echo "$line" | awk '{ print $2 }') ;
if [[ -f "$file_to_move" ]]; then
mkdir -p "$directory_to_move_to"
\gmv -b "$file_to_move" "$directory_to_move_to"
fi
done < /tmp/filesort_substring.txt
shopt -u nocasematch
where $HOME/Scripts/longest_common_substring.sh is
#!/bin/bash
shopt -s nocasematch
if ((${#1}>${#2})); then
long=$1 short=$2
else
long=$2 short=$1
fi
lshort=${#short}
score=0
for ((i=0;i<lshort-score;++i)); do
for ((l=score+1;l<=lshort-i;++l)); do
sub=${short:i:l}
[[ $long != *$sub* ]] && break
subfound=$sub score=$l
done
done
if ((score)); then
echo "$subfound"
fi
shopt -u nocasematch
Kudos to the original solution for computing the match in the script which I found elsewhere in this site

problems while reading log file with tail -n0 -F

i am monitoring the asterisk log file for peers that get offline.
the if part is working correct, but the sed command is not executed in the else part, although the echo command works. What do i need to change
tail -n0 -F /var/log/asterisk/messages | \
while read LINE
do
if echo "$LINE" | /bin/grep -q "is now UNREACHABLE!"
then
EXTEN=$(echo $LINE | /bin/grep -o -P "(?<=\').*(?=\')")
echo "$EXTEN is now UNREACHABLE!"
CALLERID=$(/bin/sed -n '/^\['"$EXTEN"'\]/,/^\[.*\]/{/^callerid*/p}' "$SIP" | /usr/bin/awk -F'=' '{ print $2 }')
if .......
then
.......
fi
elif echo "$LINE" | /bin/grep -q "is now REACHABLE!"
then
EXTEN=$(echo $LINE | /bin/grep -o -P "(?<=\').*(?=\')")
echo "$EXTEN is now REACHABLE!"
if /bin/grep -qi "^$EXTEN;" $OFFLINE; then
/bin/sed -i '/^$EXTEN;/d' $OFFLINE
fi
fi
done
You have a quoting problem - you've used single quotes when the string includes a shell variable:
if /bin/grep -qi "^$EXTEN;" $OFFLINE; then
/bin/sed -i '/^$EXTEN;/d' $OFFLINE
fi
Try using double quotes instead:
if /bin/grep -qi "^$EXTEN;" $OFFLINE; then
/bin/sed -i "/^$EXTEN;/d" $OFFLINE
fi

wc -c gives one more than I expected, why is that?

echo '2003'| wc -c
I thought it would give me 4, but it turned to be 5, what is that additional byte?
Because echo will get a new line.
echo "2014" | wc -c
it will get 5
printf "2014" | wc -c
it will get 4 where printf will not add a new line.
echo contains a built-in switch, -n, to remove newline. So running:
echo -n "2021" | wc -c
Will output the expected 4.
echo adds new line which is causing the issue.
As mentioned by "KyChen", you can use printf or:
a="2014 ;
echo $a |awk '{print length}'

NetworkManager dispatcher script

scripts in /etc/NetworkManager/dispatcher.d will got exec and parameters will be passed to the scripts by NetworkManager.
One of my laptop BIOS is malfunctioning, I have to manually sync the time, and do system upgrade BTW. I am working with a script to automate this task.
Here's the script:
#!/bin/sh
IF=$1
STATUS=$2
if [ "$STATUS"x != 'up'x -o "$(date +%Y)" -gt "2012" ] ;then
exit
fi
logger "==$0=="
wait_for_process(){
PNAME=$1
PID=`pgrep $PNAME`
while [ -z "$PID" ];do
logger "waiting $1 running for another 3 sec.."
sleep 3;
PID=`pgrep $PNAME`
done
logger "$1 is running!"
}
wait_for_process nm-applet
wait_for_process lxpanel
export DISPLAY=$(echo $DISPLAY | cut -c -2)
if [ -z $DISPLAY ];then
export DISPLAY=:0
fi
#below cmd will yield null string for $user
user=$(who | grep "$DISPLAY" | awk '{print $1}' | tail -n1)
#so I have to hardcode the user name:(
user=xxx
export XAUTHORITY="/home/$user/.Xauthority"
logger "Display $DISPLAY user $user"
su $user -c "xterm -e 'sudo /usr/bin/ntpd -qdg && sudo yaourt -Syua' &" || logger "cannot run xterm"
(the script is invoked before x window, run as root)
user=$(who | grep "$DISPLAY" | awk '{print $1}' | tail -n1) cannot find the login user name. But it works in xterm.
Can someone help?
I am using archlinux i686 + openbox + lxpanel
edit:
I want to find the real login user name, while the script is run by root.
Are you looking for the name of the user running the script? How about:
user=$( id -un )