Main Page

From CleanPosts

Revision as of 19:34, 22 February 2021 by Selah (Talk | contribs)
Jump to: navigation, search

Linux Jedi Mind Tricks

  • Linux Novice - Someone who wonders what RTFM means.
  • Linux User - Someone who has tried to RTFM.
  • Windows User - Someone who has never heard RTFM.
  • Linux Guru - Someone who doesn't need to RTFM.
  • Linux Hacker - Someone who knows what isn't in TFM.
  • Linux Jedi - The one who WTFM.


  • Burn ISO to disk

wodim -eject -tao speed=0 dev=/dev/sr0 -v -data files1.iso

  • Calculate the Lorentz factor for any velocity as a fraction of c (the speed of light)

awk 'BEGIN { for (v =0; v <=99; v++) printf "%.2f %.4f\n", v/100, 1/sqrt(1-(v / 100)^2)}'

  • Change double-spaces in a text file to single spaces

cat redpine.txt | sed 's/ \+/ /g' > redpine2.txt

  • Change the owner of a directory and all its contents

chown -R teresita DIRECTORY

  • Change the system default editor

sudo update-alternatives --config editor

  • Combine two files, line by line, comma delimited

$ paste -d, names.txt distances.txt

  • Convert a floating point number to binary

echo 'obase = 2; scale = 15; 3.141592653589793' | bc -l

  • Convert all your files saved as "*.jpg-large" back to "*.jpg" (so Twitter thinks they are images again):

find . -depth -name "*.jpg-large" -exec sh -c 'f="{}"; mv -- "$f" "${f%.jpg-large}.jpg"' \;

  • Convert a MIDI file to a .WAV file

timidity -Ow -oRUBY.WAV RUBY.MID

  • Convert a photo into an ASCII art representation directly into the terminal and save it to photo.ascii at the same time

jp2a Photo.jpg | tee photo.ascii

  • Convert ASCII diagrams to graphics

ditaa stargrid.txt stargrid.png

  • Convert .avi video files to smaller .mp4 format

ffmpeg -i 'U2 - New Years Day.avi' 'U2 - New Years Day.mp4'

  • Convert GIFs from Twitter that download as MP4s back into uploadable GIFs again

ffmpeg -y -i input.mp4 -filter_complex "scale=320:-1:flags=lanczos[x];[x]split[x1][x2]; [x1]palettegen[p];[x2][p]paletteuse" output.gif

  • Convert man page to text file

man concalc | col -bx >concalc.txt

  • Convert RPM package to DEB package

alien file.rpm

  • Convert text files from MS-DOS format to UNIX format

tr -d '\r' <MULE.ASC >mule.txt

  • Convert WordStar files to plain text

cat rubymae.ws | tr -c '[:print:]\t\r\n' '[ *]' >rubymae.txt

  • Copy a file

cp INFILE OUTFILE

  • Copy command-line output to clipboard

cat spock2.txt | xclip -selection clipboard

  • Count all MP3 files under your home directory and report total disk usage

find /home -name '*.mp3' -ls | awk '{s+=$7;f+=1}END{print " MP3 files: "f"\nTotal size: "s/1000000" MB"}'

  • Count processes running as each user:

ps -ef | awk '{print$1}' | sort | uniq -c | sort -nr

  • Create a custom command to list files

alias l = 'ls -l --color=auto'

  • Create a directory using today's date

mkdir $(date +%Y%m%d)

Create a file and a directory with unique names from the system clock: touch "$(date +"%y%m%d%H%M%S")";sleep 1; mkdir "$(date +"%y%m%d%H%M%S")"

  • Create a link

ln -s /initrd/mnt/dev_ro2 HOME

  • Remove empty directories under the working directory

find . -empty -exec rm -rf {} \;

  • Display all subdirectories in a tree format

ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//----/g' -e 's/^//' -e 's/-/|/'

  • Display time since boot

uptime

  • Display unique lines in a sorted file

uniq <FILE1 >FILE2

  • Download streaming videos and convert them to MP3s

sudo curl -L https://yt-dl.org/downloads/latest/youtube-dl -o /usr/local/bin/youtube-dl sudo chmod a+x /usr/local/bin/youtube-dl youtube-dl --title --extract-audio --audio-format mp3 https://www.youtube.com/watch?v=L3FmBjX-p0I

  • Extract audio from any video file

ffmpeg -i Pet-Shop-Boys---West-End-Girls.mp4 -vn west-end-girls.ogg

  • Extract gzip compressed tar archives

gunzip progs.tar.gz tar xvf progs.tar

  • Extract pages from a PDF to build a new PDF

ps2pdf -dFirstPage=4 -dLastPage=8 input.pdf output.pdf

  • Extract tarball

tar -xvf /dev/hda/FILE

  • Factorial function implemented by recursion.

define fact(n) { if (n <= 1) return (n); return (n * fact(n-1)); }

  • Factorial function in python

python -c 'import math; print(math.factorial(52))'

  • Find all the unique four-letter words in a text file

cat love.txt | perl -ne 'print map("$_\n", m/\w+/g);' | tr A-Z a-z | sort | uniq | awk 'length($1) == 4 {print}'

  • Find duplicates on your filesystem

duff -r *

  • Find files by name

find . -name *wav -print

  • Find man page for a command

whereis -m genisoimage genisoimage: /usr/share/man/man1/genisoimage.1.gz

  • Find ten biggest hogs of disk space under a directory

du -s /usr/share/* | sort -nr | head

  • Find text in a file

awk 'chevy' cars.txt

  • Format floppy disk

fdformat /dev/sde

  • Generate a pdf from a man page

man -t vim | ps2pdf - > vim.pdf

  • Generate a random password

openssl rand -base64 12

FRYSkfIikVA7AuNm

openssl rand -base64 24

l8Ht0b83wCAnH95izexZStOW73IqH/Mz

  • Get a one-line description for all the files in a directory, delete lines that have no description

ls -l /usr/bin | awk '{print $9}' | xargs whatis | sed '/appropriate/d'

  • Get a weather forecast for your city

curl wttr.in/seattle

  • Get information about all files of a certain type

find . -name *com -exec file {} \;

  • Get the sizes of all subdirectories under a directory

du -sh MYDIR

  • Get your public IP address

curl ifconfig.me; echo

  • Grab a copy of a website

wget -w9 -r --random-wait -l3 -np -E https://rosettacode.org/wiki/Rosetta_Code

  • List actual files referenced by library symbolic links

sudo ls -lR /lib | grep ^l | awk '{print $9" "$10" "$11}' | grep ^lib | sort

  • List all processes by owner, sort on PID, omit header

ps -ef | awk '{print$1}' | sort | uniq -c | sort -nr | sed '/UID/d'

  • List directories

find . -type d -print

  • List only non-blank lines in a file

awk 'NF >0' file.txt

  • List the files in the working directory (Python)
>>> import os
>>> print('\n'.join(sorted(os.listdir('.'))))
  • List the misspelled words in a file

enchant -l matthew

  • MAGA twitter account name generator

for ((i=1; i<=10; i+=1)); do python -c 'import random; print("PutinBot"+str(random.randint(100000,900000-1)))'; done

  • Make a file executable for all users

chmod u+x FILE

  • Make a file lowercase

cat FILE1.TXT | tr '[A-Z]' '[a-z]' > FILE2.TXT

  • Make an image of a CD on your hard drive

dd if=/dev/sr0 of=image.iso

  • Make archive

tar -c DIRECTORY | bzip2 > DIR.TAR.BZ2

  • Make directories for 36 months using brace expansion:

mkdir {2021..2023}-{01..12}

  • Make ISO from temp directory

genisoimage -r -joliet-long -o files1.iso temp

  • Make the ls command print in a tree format

alias tree="ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^//' -e 's/-/|/'"

  • Make the ls command useful for a change

alias ls='ls -lhGpt --color=always'

  • Make the text in a file all uppercase

cat testa.txt | tr '[a-z]' '[A-Z]' > testb.txt

  • Mount that image on your system to use it

(The mount point must already exist) mount -o loop image.iso /mnt/temp

  • Mount your SquashFS file

mount -o loop -t squashfs PUP_412.SFS /mnt/pup


  • Move all files starting with "B" into the b subdirectory

find -name "B*.*" -exec mv {} b \;

  • Move all the .jpg images from one folder to another folder, recursively

find www.cleanposts.com -type f -name *.jpg -exec mv '{}' /home/teresita/Downloads \;

  • MP3 to WAV conversion

madplay --output=wave:OCEANLAB.WAV OCEANLAB.MP3

  • Prime factors of first 100 integers

echo {1..100} | factor

  • Print a complete date-time group

date '+%Y-%m-%d/%k:%M:%S'

  • Print all lines with exactly 40 characters

awk 'length ==40' tags.tx3

  • Print all prime numbers between 1 and 5000

seq 1 5000 | factor | awk 'NF==2 { print $2 }' | tr '\n' ',';echo

  • Print a random line from a file of unknown length

awk 'BEGIN{ srand() }; rand() * NR < 1 { line = $0} END {print line}' tags.tx3

  • Print a short list of your most recently-used commands

fc -rl | awk '{print $1=""; print}'

  • Print lines with only four letter words (or less)

awk 'length < 5' tags.tx3

  • Print number of processes running as each user

$ ps -ef | awk '{print $1}' | sort | uniq -c

  • Print sizes of files in current directory with commas for readability

ls -lp | grep -v / | awk '{$1=$2=$3=$4=$6=$7=$8="";print}' | sed -e :a -e 's/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/;ta'

  • Print the current month in Julian dates

cal -j

  • Print the first sixteen binary numbers using awk to align the data

echo "obase=2;i=0;while(i<=15) {i;i+=1}" | bc | awk '{printf "%4s\n", $0}'

  • Print the lines of file2 that are missing in file1

grep -vxFf file1.txt file2.txt

  • Print the squares and cubes of the integers from 0 to 10

python -c 'print([i**2 for i in range(11)]);print([i**3 for i in range(11)])'

  • Print the unique commands in your history by removing duplicate lines in place without an alphabetical sort

history | awk '{$1="";print}' | awk '!a[$0]++'

or:

history | awk '{$1=""} !a[$0]++'

  • Print working directory file permissions, sizes, and names, formatted with awk

ls -l | awk '{$5=sprintf("%9s",$5); printf "%s %9s", substr($1,1,4),$5" "; for (i=9;i<=NF;i++) printf $i" "; printf "\n"}'

  • Print your command history, omitting duplicates

history | awk '{$1="";print }' | sort | uniq

  • Print your top fifteen most frequently-used commands:

history | awk '{print $2}' | sort | uniq -c | sort -n | tail -n15 | sort -nr

  • Recursively move mp3 files in many directories to a single target directory

find -name '*.mp3' -exec mv -i {} /home/minix/Desktop/music \;

  • Remove tags from HTML file

sed -e :a -e 's/<[^<]*>/ /g;/</{N;s/\n/ /;ba;}' CleanPosts.html

  • Rename all files with extension .OUT with the extension .txt

rename 's/\.OUT$/.txt/' *

  • Replace spaces in a filename with hyphens

find . -name "* *mp3" -exec rename 's/\ /-/g' {} \;

  • Replace spaces in the filename of all the files in a directory with hyphens

find . -name "* *mp3" -exec rename 's/\ /-/g' {} \;

  • Return the name of the most-recently modified file in a directory

$ ls -t | head -1

  • Reverse the order of the fields on each line

awk '{for (i=NF;i>0;i--){printf $i" "};printf "\n"}' gettysburg2.txt

  • Run the last command again as root

sudo !!

  • Search for "foo" and "bar" in any order

awk '/foo/ && /bar/' tags.txt

  • Search for "foo" and "bar" in that order

awk '/foo.*bar/' tags.txt

  • See what's eating your system clocks

ps aux --sort %cpu | awk '{print $3,$1,$11}' | tail -30

  • Send a man page to the terminal minus the embedded backspace characters

man genisoimage | col -b | less

  • Show all mounted media

lsblk | awk 'NF >6 {print$1,"\t",$4,"\t",$7}'

  • Shuffle, deal 4 hands

python -c "num=['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']*4; suit=['h','d','c','s']*13; card=[x+y for x,y in zip(num, suit)]; import random as r; r.shuffle(card); print card[1:6];print card[7:12];print card[13:18];print card[18:23]"

  • Sort user processes by memory footprint

ps aux --sort -%mem | awk '{print $4,$1,$11}' | sed '/root/d' | head -50

  • Strip blank lines from a text file

awk 'NF > 0' yeshua > yeshua2

  • Strip carriage returns from a DOS file

tr -d '\015' <INFILE >OUTFILE

  • Tally up a column of figures

awk '{s+=$1} END {print s}' figures.txt

  • Tally up bytes of all files in a directory

ls -l | sed '/^d/d' | awk '{ x += $5 } ; END { print "Total bytes: " x }'

  • Tally up bytes of selected files in a directory

du -b *.msg | awk '{s+=$1} END {print s}'

  • Turn a directory into a SquashFS file

mksquashfs /tmp/merge PUP_412.SFS

  • Turn the capslock key into a second ESC key

setxkbmap -option caps:escape

  • Upload a file to your webspace

wput MYFILE ftp://username:password@web.host.com

  • Use awk and the command-line factor program to print prime numbers

echo {1..80} | factor | awk 'NF==2 { print $2 }'

  • Use awk like grep

awk '/sex/' tags.txt

  • Use imagemagick to take a screen shot

import screenshot.jpg

  • Use CUPS printer management system

localhost:631 (in a browser address bar)

  • Use the command line as a quick calculator
echo $((145+5))
echo $((145-5))
echo $((145*5))
echo $((145/5))
echo $((145%5))
echo $((145**5))
  • Use Vorbis Tools to convert a .WAV file to .ogg format

oggenc synthony.wav

  • View a text file with line numbers added

grep -n ^ countzero.txt | less

  • Your top 25 commands

history | awk '{print $2}' | sort | uniq -c | sort -nr | head -25

  • Scripts
  • Arc length of a parabola
#!/usr/bin/python3

import math

h = float(input("Enter parabola height: "))
w = float(input("Enter parabola width: "))

l = math.log(((4 * h) + math.sqrt(w**2+ 16 * h**2)) / w) * w**2 / (8 * h) + (math.sqrt((w**2 + 16 * h **2))) / 2

print(f"Parabola arc length = {l}")


  • Calculate absolute magnitude from visual magnitude and radial distance in light-years
#!/usr/bin/python

import math
import sys 

Mvis = float(sys.argv[1])
Dist = float(sys.argv[2])

Vabs = Mvis - 5 * (math.log10(Dist /  3.2616) -1)

print round(Vabs,3)
  • Calculate days between two dates (accounts for leap years)
#!/usr/bin/python

import sys
from datetime import date

y1=int(sys.argv[1])
m1=int(sys.argv[2])
d1=int(sys.argv[3])
y2=int(sys.argv[4])
m2=int(sys.argv[5])
d2=int(sys.argv[6])

x = date(y1,m1,d1)
y = date(y2,m2,d2)
z = y - x
print (z.days)
  • Calculate Pi using Nilakantha's series
#!/usr/bin/python

from decimal import *
import sys

getcontext().prec = 40

c = 0
s = Decimal(1);  
pi = Decimal(3); 

n = int(sys.argv[1])

for i in range(2, n * 2, 2):
    pi = pi + s * (Decimal(4) / (Decimal(i) * (Decimal(i) + Decimal(1)) * (Decimal(i) + Decimal(2))))
    s = -1 * s
    c = c + 1
    print c, (pi)
  • Calculate the convergent factorial series ∑1/𝑛! = 1/1! + 1/2! + 1/3!+...
#!/usr/bin/python
import sys
import math

n = 1
for x in range (1, int(sys.argv[1])):
    n = n + (1 / float(math.factorial(x)))
    print (n)
  • Calculate the factors of a number in Python
#!/usr/bin/python 

import sys 

n=int(sys.argv[1]) 

factors = [] 

for i in range(1,n+1): 
    if n%i == 0: 
        factors.append(i) 

print (factors)


  • Calculate the gamma function over a range
#!/usr/bin/python

import sys
import math
from numpy import arange

start = float(sys.argv[1])
stop = float(sys.argv[2])
step = float(sys.argv[3])

for x in arange(start, stop, step):
    print (round(x,2),round(math.gamma(x),8))
  • Compile and install software old-school, from downloaded source code
tar -xvf joe-4.6.tar.gz 
cd joe* 
./configure 
make 
sudo make install
  • Convert between numerical bases
#!/bin/bash
printf "hex2dec=";echo "ibase=16;$1"|bc
printf "dec2hex=";echo "obase=16;$1"|bc
printf "oct2dec=";echo "ibase=8;$1"|bc
printf "dec2oct=";echo "obase=8;$1"|bc
  • Convert decimal to 16 bit binary and trim leading zeros
#! /bin/bash
D2B=({0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1})
echo $((10#${D2B[$1]}))
  • Convert temperatures
#!/bin/bash
c=$(echo "scale=1;($1-32)*(5/9)" | bc -l)
f=$(echo "scale=1;($1*(9/5))+32" | bc -l)
echo -e "\n\e[1;30m=$c C & $f F\e[0m\n"
  • Cosine by series
#!/usr/bin/python3

import sys
import math

x = float(sys.argv[1])

def cosine(x,y):
    cos = 0
    for n in range (y):
        cos += ((-1)**n) * (x ** (2*n)) / (math.factorial(2 * n))
    return cos

for i in range (1,16):
    print (math.cos(x),cosine(x,i))
  • Find all palindromic words in a file
#!/usr/bin/python

def words(fileobj):
    for line in fileobj:
        for word in line.split():
            yield word

with open("words.txt") as wordfile:
     wordgen = words(wordfile)
     for word in wordgen:
         if word == word[::-1]:
              print(word),
  • Find all permutations of a string
#!/usr/bin/python

import sys
from math import factorial

s = sys.argv[1]

from math import factorial 
    
def perm(s): 
    for i in range(factorial(len(s))):          
        print(''.join(s))   
        p=len(s)-1
        while (p > 0) and (s[p-1] > s[p]):        
            p=p-1
        s[p:] = reversed(s[p:]) 
        if p > 0: 
            q = p 
            while s[p-1] > s[q]:   
                q=q+1
        s[p-1],s[q]=s[q],s[p-1]
   

s = list(s) 
s.sort() 
perm(s)
  • Find the limit, as x approaches 0, of f(x) = tan x / x
#!/usr/bin/python2.7
import math
import numpy as np

for x in np.arange(1.0, 0, -0.01):
    print((math.tan(x))/x)
  • Five dolla quick pick Lotto
#!/usr/bin/python3

import random
random.seed()
items = [*range(1,50)]

for i in range (0,10):
    print (random.sample(items,6))
  • Hohmann time of flight, days
#!/usr/bin/python3

import sys
import math 

au = 149598023
mu = 1.32712E11
r1 = au * float(sys.argv[1])
r2 = au * float(sys.argv[2])
e = (r1 + r2)**3
f = mu * 8
i = math.pi * math.sqrt(e / f)
print (round((i / 3600 / 24),2))
  • Integration
Python 3.8.5 (default, Jul 28 2020, 12:59:40) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> from scipy import integrate
>>> x = np.arange(0,10)
>>> y = np.sqrt(x)
>>> z = integrate.simps(y,x)
>>> print(z)
17.875036119764566
  • List primes between 2 and any number
#!/bin/bash
for (( i=2; i<=$1; i++ ));do
l=$(factor $i | cut -d : -f 1)
r=$(factor $i | cut -d : -f 2 | sed 's/ //g')
if (( $l == $r ));then
echo $i
fi
done
  • Loop through a range
#!/usr/bin/python3

for i in range(2, 9, 2):
    print("%d " % i, end="")
print("who do we appreciate?")
  • Make all filenames in a directory lowercase
#!/bin/bash 
for x in `ls` 
do 
if [ ! -f $x ]; then 
continue 
fi 
lc=`echo $x | tr '[A-Z]' '[a-z]'` 
if [ $lc != $x ]; then 
mv -i $x $lc 
fi 
done 

paste into file called lowerit chmod u+x lowerit ./lowerit

  • Make a new file of the individual words in another file

tr ' ' '\012' <INFILE >OUTFILE

or

for WORD in `cat FILE`
do
echo $WORD
done
  • Find the mean of a set of numbers of any length
#!/usr/bin/python

from numpy import mean
import sys

figures = [float(elements) for elements in sys.argv[1:]]
average = mean(figures)
print ("The average is", round(average,4))
  • Find the point of intersection of two co-planar lines defined by four points
#!/usr/bin/python

import sys

def line_intersect(Ax1, Ay1, Ax2, Ay2, Bx1, By1, Bx2, By2):
    d = (By2 - By1) * (Ax2 - Ax1) - (Bx2 - Bx1) * (Ay2 - Ay1)
    if d:
        uA = ((Bx2 - Bx1) * (Ay1 - By1) - (By2 - By1) * (Ax1 - Bx1)) / d
        uB = ((Ax2 - Ax1) * (Ay1 - By1) - (Ay2 - Ay1) * (Ax1 - Bx1)) / d
    else:
        return
    if not(0 <= uA <= 1 and 0 <= uB <= 1):
        return
    x = Ax1 + uA * (Ax2 - Ax1)
    y = Ay1 + uA * (Ay2 - Ay1)
 
    return x, y
 
a = float(sys.argv[1])
b = float(sys.argv[2])
c = float(sys.argv[3])
d = float(sys.argv[4])
e = float(sys.argv[5])
f = float(sys.argv[6])
g = float(sys.argv[7])
h = float(sys.argv[8])

pt = line_intersect(a, b, c, d, e, f, g, h)
print(pt)
  • Python script to convert polar coordinates (right ascension, declination) to Cartesian coordinates (x,y,z)
#!/usr/bin/python

import math
import sys

rah=float(sys.argv[1])
ram=float(sys.argv[2])
ras=float(sys.argv[3])
ded=float(sys.argv[4])
dem=float(sys.argv[5])
des=float(sys.argv[6])
dis=float(sys.argv[7])

alpha=rah*15+ram/4+ras/240
delta=ded+dem/60+des/3600

alpharad=math.radians(alpha)
deltarad=math.radians(delta)

x=dis*math.cos(deltarad)*math.cos(alpharad)
y=dis*math.cos(deltarad)*math.sin(alpharad)
z=dis*math.sin(deltarad) 

print 'x =',x,'y =',y,'z =',z
  • Perform a ROT 13 conversion
#!/bin/sh
echo "$1" | tr '[A-Za-z]' '[N-ZA-Mn-za-m]'
  • Print the first n Fibonacci numbers
#!/usr/bin/python

import sys

def fib(n,x=[0,1]):
   for i in range(abs(n)-1): x=[x[1],sum(x)]
   return x[1]*pow(-1,abs(n)-1) if n<0 else x[1] if n else 0
 
for i in range(1,int(sys.argv[1])): print fib(i)
  • Rename in bulk
OLD=xxx
NEW=yyy
for F in $OLD*
do
SUFFIX=`expr $F : '$OLD\(.*\)'`
mv $OLD$SUFFIX $NEW$SUFFIX
done
  • Return pi to the number of digits specified on the command line

(Answer grows more accurate the longer the fractional part)

#!/bin/bash 
echo "scale=$1;a(1)*4" | bc -l
  • Return slope-intercept form of the equation of a line through two points
#!/usr/bin/python

import sys

x1=float(sys.argv[1])
y1=float(sys.argv[2])
x2=float(sys.argv[3])
y2=float(sys.argv[4])

m = (y2-y1)/(x2-x1)
b = y1 / (m * x1)

print 'y =',m,'x +',b

or

from sys import argv

x1, y1, x2, y2 = [float(f) for f in argv[1:]]

m = (y2 - y1) / (x2 - x1)
b = y1 / (m * x1)

print(f"y = {m} x + {b}")
  • Show ASCII table
# Usage: awk -f showascii
BEGIN {
    for (i=0; i<16; i++) {
      for (j=32+i; j<128; j+=16) {
        if (j == 32) { x = "SPC" }
        else if (j == 127) { x = "DEL" }
        else { x = sprintf("%c",j) }
        printf("%3d: %-5s",j,x)
      }
      print ""
    }
}
  • Synodic period between two planets (how many days until the inside planet laps the outside planet)
#!/usr/bin/python

import sys 

inside = float(sys.argv[1])
outside = float(sys.argv[2])

interim1 = inside / outside
if interim1 < 1: 
   interim1 = 1 / interim1
interim2 = 1 - interim1
print ((abs(1 / interim2) + 1) * inside)


  • Tally up a column of figures
#! /bin/sh
case "$1" in 
[1-9]*) colnum="$1"; shift;; 
*) echo "Usage: `basename $0` colnum [files]" 1>&2; exit 1;; 
esac 
awk '{sum += $col} 
END {print sum}' col=$colnum OFMT='%.2f' ${1+"$@"}
  • Use awk to list the thirty most-common words in a text file
#Usage: awk -f wordfreq textfile.txt

{   nbytes += length($0) + 2 # +2 for CR/LF
    nfields += NF
    $0 = tolower($0)
    for (i=1; i<=NF; i++) {
      arr[$i]++
    }
}
END {
    show = (show == "") ? 30 : show
    width1 = length(show)
    PROCINFO["sorted_in"] = "@val_num_desc"
    for (i in arr) {
      if (width2 == 0) { width2 = length(arr[i]) }
      if (n++ >= show) { break }
      printf("%*d %*d %s\n",width1,n,width2,arr[i],i)
    }
    printf("input: %d records, %d bytes, %d words of which %d are unique\n",NR,nbytes,nfields,length(arr))
    exit(0)
}
Personal tools
Strangers In Paradise