You are not logged in.

#1526 2011-08-22 18:07:00

inknoir
Member
Registered: 2009-06-28
Posts: 29

Re: Post your handy self made command line utilities

Hi Archlinux,

I call this the poor man's comicviewer for cbr-/cbz-files:

#!/bin/bash                                                                      
DIRECTORY="$1"                                                                   
if [ ! -d "$DIRECTORY" ]; then                                                   
   mkdir /tmp/"$DIRECTORY"                                                       
fi                                                                               
aunpack -X "/tmp/$DIRECTORY" "$1" && sxiv -r -z 70 "/tmp/$DIRECTORY"/*                

You need only atool and sxiv.

edit: thanks to steve___ it works now with sxiv, which is better than feh for this purpose.

Last edited by inknoir (2011-08-24 10:14:04)

Offline

#1527 2011-08-22 18:10:39

steve___
Member
Registered: 2008-02-24
Posts: 452

Re: Post your handy self made command line utilities

@inknoir - Have your tried, sxiv?  Just a thought.

Offline

#1528 2011-08-22 19:08:52

inknoir
Member
Registered: 2009-06-28
Posts: 29

Re: Post your handy self made command line utilities

@steve___

Yes, although I tried sxiv only for a couple of hours. In these few hours couldn't find a way to fit to width (or set a certain width) while keeping the aspectratio in sxiv either. Maybe you can help me? I would love to use sxiv.

Offline

#1529 2011-08-22 19:40:12

steve___
Member
Registered: 2008-02-24
Posts: 452

Re: Post your handy self made command line utilities

what wm are you using?  sxiv and dwm worked for me.  I used this script to test:

#!/bin/bash

rm -rf /tmp/cr &>/dev/null
mkdir /tmp/cr
cp "$1" /tmp
unzip "/tmp/$1" -d /tmp/cr &>/dev/null
sxiv /tmp/cr/*/*

Last edited by steve___ (2011-08-22 19:41:52)

Offline

#1530 2011-08-22 20:24:44

inknoir
Member
Registered: 2009-06-28
Posts: 29

Re: Post your handy self made command line utilities

@steve___
I use i3wm, sometimes dwm. But the point is not the extracting but the viewing part. I can't get sxiv to view the jpegs in a certain way. The single picture should be shown with the width, the screen has (1024 pixel in my case). But aspectratio shouldn't change, so part of the picture is off the screen. It should fit to width. And it would be neat, if the pictureviewer could start each picture/page from top/the beginning. So you open the first pic, scroll down to the bottom, switch to the next pic, scroll down to bottom and so on.
Here is an examplefile for testing: creativecommonslineced_comic

Offline

#1531 2011-08-22 20:34:35

steve___
Member
Registered: 2008-02-24
Posts: 452

Re: Post your handy self made command line utilities

To fit page width I used 'sxiv -x 70 *' (for my terminal).   I have to scroll right on images that are double pages but otherwise it works.  If you want to talk more, email me, so we do not fill up this thread with our correspondence.

Offline

#1532 2011-08-24 06:25:10

Procyon
Member
Registered: 2008-05-07
Posts: 1,819

Re: Post your handy self made command line utilities

Cue player in bash.
.cue files are read without external applications.
They are found with **/*.cue, so run it in the right directory.
Uses mplayer in -slave mode to play the associated music file.
If the FILE field doesn't point to the right file, it will find a tta/mp3/ogg file in the .cue's directory instead.

Screenshot: http://ompldr.org/vYTEzcA

Writes some cue* files for itself in /tmp, and when quitting a session file named "session" to the current working dir, which stores the time and .cue it left off at.
No interactive controls at all. Use "cueplayer help" to see a list of commands.

#! /bin/bash
shopt -s nullglob globstar nocaseglob

function stripq() {
	local temp
	temp=${!1}
	temp=${temp#\"}
	temp=${temp%\"}
	printf -v $1 "%s" "$temp"
}

function index2mplayer() {
	#mplayer time is seconds.deciseconds from which the . will be stripped
	#index time is in minutes:seconds:centiseconds
	local minutes temp
	temp=${!1}
	minutes=${temp%%:*}
	minutes=${minutes#0}
	temp=${temp#*:}
	temp=${temp%?}
	temp=${temp//:}
	temp=${temp#0}
	temp=${temp#0}
	temp=${temp#0} #annoying octal notation!
	printf -v $1 "%d" "$((minutes * 600 + temp))"
}

function readcue() {
	IFS=$'\n\t '
	for encoding in sjis utf8 unknown; do
		iconv -f $encoding -t utf8 "$1" &>/dev/null && break
	done
	[[ $encoding = unknown ]] && echo UNKNOWN ENCODING && exit
	track=0
	titlelist=( )
	artistlist=( )
	indexlist=( )
	while read line; do
		type=${line%% *}
		value=${line#* }
		[[ ${value: -1} != \" ]] && value=${value% *}
		extra=${line##* }
		[[ $type = PERFORMER && $track = 0 ]] && stripq value && albumartist=$value
		if [[ $type = FILE ]]; then
			stripq value
			file=$value
			dir=$(dirname "$1")
			if ! [[ -f "$dir/$file" ]]; then
				for extension in tta mp3 ogg unknown; do
					newfile=$(find "$dir" -type f -iname "*$extension")
					[[ -f "$newfile" ]] && file=$newfile && echo "Found the file: $file" && break
				done
				if [[ $extension = unknown ]]; then
					echo File: "$file"
					read -n1 -p "Was not able to find the file. Continue?" < /dev/tty
					[[ $REPLY = y ]] || exit
				fi
			fi
		fi
		[[ $type = TITLE && $track = 0 ]] && stripq value && album=$value
		[[ $type = TRACK ]] && track=${value#0}
		[[ $type = TITLE && $track != 0 ]] && stripq value && titlelist[$track]=$value
		[[ $type = PERFORMER && track != 0 ]] && stripq value && artistlist[$track]=$value
		[[ $type = INDEX ]] && index2mplayer extra && indexlist[$track]=$extra
	done < <(iconv -f $encoding -t utf8 "$1" | sed 's/\r$//')
	IFS=$'\n'
}

function getpos() {
	local newpos=none
	while ! [[ "$newpos" =~ ANS_TIME ]]; do
		echo get_time_pos > $fifo
		newpos=$(tail -n 1 $fifo.answer)
		[[ "$newpos" =~ "EOF code: 1" ]] && { pos=-1; echo > $fifo.answer; return; } #fifo.answer is cleared to stop the next one from erroneously reading another EOF, and to reduce filesize.
		pos=${newpos#ANS_TIME_POSITION=}
		pos=${pos//.}
		sleep 0.1
	done
	pos=${pos#0}
}

function getlen() {
	local newlen=none
	while ! [[ "$newlen" =~ ANS_LENGTH ]]; do
		echo get_time_length > $fifo
		newlen=$(tail -n 1 $fifo.answer)
		len=${newlen#ANS_LENGTH=}
		len=${len//.}
		sleep 0.1
	done
	len=${len#0}
}

function ispaused() {
	local state=none
	while ! [[ "$state" =~ ANS_pause ]]; do
		echo get_property pause > $fifo
		state=$(tail -n 1 $fifo.answer)
	done
	[[ "$state" =~ =yes ]]
}

function pause() {
	ispaused || echo pause > $fifo
}

fifo=/tmp/cueplayer_in

if [[ $# != 0 ]]; then
	! [[ -e $fifo ]] && ! [[ "$1" == help || "$1" == "--help" || "$1" == "-h" ]] && echo "Not running" && exit
	case "$1" in
	pause)		pause;;					#pause (not toggle)
	ispaused)	ispaused && echo yes || echo no;; 	#prints "yes" if paused or "no" if playing
	toggle)		echo pause > $fifo;; 			#toggles pause / play
	play)		{ ispaused && echo pause > $fifo; };;	#plays if paused
	next)		echo seek $(cat /tmp/cuenext) 2 > $fifo && echo change=0 > /tmp/cuecommand;;	#play next song
	prev)		echo seek $(cat /tmp/cueprev) 2 > $fifo && echo change=0 > /tmp/cuecommand;;	#play previous song, if 10 seconds into current song, rewind to start of current song instead
	prevalbum)	echo ChangeAlbum=-1 > /tmp/cuecommand;;	#play previous album
	nextalbum)	echo ChangeAlbum=1 > /tmp/cuecommand;;	#play next album
	up10)		echo seek 10 0 > $fifo && echo change=0 > /tmp/cuecommand;;	#seek forward 10 seconds
	down10)		echo seek -10 0 > $fifo && echo change=0 > /tmp/cuecommand;;	#seek backward 10 seconds
	report)		cat /tmp/cuereport;;			#print Title :: Album \n Artist :: Filename
	help|-h|--help)	echo Usage: $(basename "$0") COMMAND. List of commands:	#Print this help
			sed -n '/case'" "'"$1"/,/--help/{s/).*#/:\t\t/p;t;s/).*//p}' "$0"
			;;
	esac
	exit
fi

[[ -e "$fifo" ]] && echo "cue player already running" && exit
trap 'tput smam; tput cnorm; loopstop=1; echo -e "\e[10B"; echo "${pos%?}" > session; echo "$cue" >> session; echo quit > $fifo; rm -v $fifo; rm -v $fifo.answer' TERM HUP EXIT
mkfifo "$fifo"
/usr/bin/mplayer -noconfig all -nolirc -ao alsa -af resample=48000:1:2 -cache 50000 -cache-min 30 -cache-seek-min 30 -softvol -softvol-max 900 -volstep 1 -msglevel all=0:global=6 -volume 5 -slave -idle -input file=$fifo >$fifo.answer 2>/dev/null &

mpid=$!

tput civis
tput rmam
recover=$(tput rc)
save=$(tput sc)
[[ -f session ]] && seekme=$(head -n 1 session) && playme=$(tail -n 1 session)

IFS=$'\n'
index=0
indexskip=-1
for cue in **/*.cue; do
	cuelist+=("$cue")
	if [[ "$playme" == "$cue" ]]; then
		indexskip=$index
		echo Found the cue of your old session.
	fi
	((index++))
done

[[ "$playme" && $indexskip = -1 ]] && echo Unable to restore session... && exit

loopstop=0
(( indexskip != -1 )) && index=$indexskip || index=0
while (( index < ${#cuelist[@]} && index >= 0 )) && ps -p $mpid &>/dev/null; do
	clear
	titlelist=( )
	artistlist=( )
	indexlist=( )
	cue=${cuelist[$index]}
	if [[ "$playme" ]]; then
		echo Continuing with "$playme"
		echo at position: "$seekme"
		unset playme
		doseek=1
		change=0
	fi
	echo "Reading $cue..."
	readcue "$cue"
	echo "Trying $file..."
	dir=$(dirname "$cue")
	if [[ -f "$dir/$file" ]]; then
		file=$dir/$file
	elif ! [[ -f "$file" ]]; then
		echo Can\'t find it...
		read -n1 -p 'Continue?' < /dev/tty
		[[ $REPLY = n ]] && exit
	fi
	echo Loading "$file"
	echo "loadfile \"$file\"" > $fifo
	echo
	echo
	echo Waiting for playback to start
	sleep 1
	getpos
	echo -ne '\e[2J\e[0;0H'
	lines=0
	cols=0
	[[ $doseek = 1 ]] && echo seek $seekme 2 > $fifo && doseek=0 && change=0
	getlen
	while (( pos != -1 )); do
		[[ -f /tmp/cuecommand ]] && source /tmp/cuecommand && rm /tmp/cuecommand
		[[ $ChangeAlbum == -1 ]] && ((index--)) && ChangeAlbum=0 && break
		[[ $ChangeAlbum == 1 ]] && ((index++)) && ChangeAlbum=0 && break
		(( loopstop == 1 )) && break
		newlines=$(tput lines)
		newcols=$(tput cols)
		(( newlines != lines || newcols != cols )) && change=0 && lines=$newlines && cols=$newcols
		if (( pos > change )); then
			echo -ne '\e[2J\e[0;0H'
			echo "Current CUE:	$cue"
			echo "File:		$file"
			(( index == 0 )) && echo "Previous CUE:" || \
			echo "Previous CUE:	${cuelist[$((index-1))]}"
			echo "Next CUE:	${cuelist[$((index+1))]}"
			echo
			echo "$album by $albumartist"
			for n in ${!titlelist[@]}; do #Note that n starts at 1!
				now=${indexlist[$n]}
				next=${indexlist[$((n+1))]}
				(( pos >= now && pos < ${next:=$len} )) && change=$next && dostore=$save$'\e[7m' || dostore=
				printf "%s%-10.10s%s\n" "$dostore" "$([[ ${#now} == 1 ]] && echo $now || echo ${now%?})" "$n. ${artistlist[$n]} - ${titlelist[$n]}"$'\e[m'
				if [[ $dostore ]]; then
					currentstart=$now
					currentnext=$next
					(( n > 2 )) && beforenow=${indexlist[$((n-1))]} || beforenow=00
					echo ${beforenow%?} > /tmp/cueprev
					echo ${next%?} > /tmp/cuenext
					echo "${titlelist[$n]} :: $album" > /tmp/cuereport
					echo "${artistlist[$n]} :: $file" >> /tmp/cuereport
				fi
			done
			echo ${len%??}
		fi
		(( pos -100 > currentstart )) && echo ${currentstart%?} > /tmp/cueprev
		printf "%s%-10.10s%s" "$recover"$'\e[7m' "${pos%?}" $'\e[m'
		sleep 1
		getpos
	done
	(( loopstop == 1 )) && break
	(( pos == -1 )) && ((index++)) && pos=0
done

Last edited by Procyon (2011-08-24 07:31:39)

Offline

#1533 2011-08-24 08:34:18

Wintervenom
Member
Registered: 2008-08-20
Posts: 1,011

Re: Post your handy self made command line utilities

A little session manager to quickly change between window managers on-the-fly without having to kill any currently-open windows.

[http://pastebin.com/gYTWj7Gu]

Last edited by Wintervenom (2011-08-24 08:35:05)

Offline

#1534 2011-08-24 20:28:42

Procyon
Member
Registered: 2008-05-07
Posts: 1,819

Re: Post your handy self made command line utilities

Here's a small system monitor.

Uses an update to the kanji background script I posted above (screenshot applies to this too).

The three columns for CPU / MEM / Download / Upload / Temp show: current | lowest this minute | highest this minute

#! /bin/bash
shopt -s nullglob

tput civis
trap "tput cnorm; exit" INT TERM EXIT

function calcpauses() {
	while read -n 1; do
		if [[ $old != $REPLY ]]; then
			if [[ $old == '' ]]; then
				echo
				counter=-1
			else
				((counter!=0))
				echo -n $counter\ 
			fi
			counter=0
		fi
		((++counter))
		old=$REPLY
	done | tail -n +2
}

#date +%w => 0 == Sunday	
kanjiday[0]=$( echo '
......#############
......#############
......##.........##
......##.........##
......##.........##
......#############
......##.........##
......##.........##
......##.........##
......#############
......#############' | calcpauses)
kanjiday[1]=$( echo '
......#############
......#############
......##.........##
......##.........##
......#############
......##.........##
......##.........##
......#############
......##.........##
.....###.........##
....###.........###' | calcpauses)
kanjiday[2]=$( echo '
...........#.......
.......#...#......#
......##...##....##
......##...##...##.
......#....##...#..
...........###.....
..........#..#......
.........##..##....
........##....##...
.......##......##..
.....###........###.' | calcpauses)
kanjiday[3]=$( echo '
...........##.......
...........##.......
...........##.....#
.....#####.##....##
......####.##...##.
.........#.###.##..
........##.####....
.......##..##.##...
......##...##..##..
......#....##...##.
..........##.....##' | calcpauses)
kanjiday[4]=$( echo '
...........##......
...........##......
...........##......
.....##############
......############.
..........####.....
.........######....
........##.##.##...
.......##..##..##..
......##...##...##.
.....##....##....##' | calcpauses)
kanjiday[5]=$( echo '
...........##......
.......####..####..
.....##..........##
...................
.....##############
...........##......
.....##############
......#....##....#.
.......#...##...#..
.......#...##...#..
.....##############' | calcpauses)
kanjiday[6]=$( echo '
...........##......
...........##......
...........##......
........########...
.......##########..
...........##......
...........##......
...........##......
...........##......
.....##############
.....##############' | calcpauses)

function kanji_background() {
	local search match line color mark counter ln=1
	IFS=$'\n'
	DAYTOTAL=
	for line in ${kanjiday[$DAYNR]}; do
		IFS=' '
		search="$((ln++)){s/"
		match=
		mark=no
		counter=1
		for color in $line; do
			search+='\(.\{'$color'\}\)'
			[[ $mark = no ]] && {
				match+='\'$((counter++))
				mark=yes
			} || {
				match+='\x1b[44m\'$((counter++))'\x1b[m'
				mark=no
			}
		done
		DAYTOTAL+="$search/$match/};"
	done
	IFS=$'\n\t '
}

function lohi() {
	LO=999999
	HI=0
	local index
	for index in "$@"; do
		((index<LO)) && LO=$index
		((index>HI)) && HI=$index
	done
}

function updatedata_persecond() {
	#TEMP
	read TEMP < /sys/class/thermal/thermal_zone0/temp
	TEMP=$((TEMP/1000))

	#DOWN
	totaldown=0
	for network in /sys/class/net/{eth,wlan}*/statistics/rx_bytes; do
		read network < $network
		(( totaldown+=network ))
	done
	(( oldtotaldown != 0 )) && DOWN=$(( (totaldown - oldtotaldown) /1024)) || DOWN=0
	oldtotaldown=$totaldown
	
	#UP
	totalup=0
	for network in /sys/class/net/{eth,wlan}*/statistics/tx_bytes; do
		read network < $network
		(( totalup+=network ))
	done
	(( oldtotalup != 0 )) && UP=$(( (totalup - oldtotalup) /1024)) || UP=0
	oldtotalup=$totalup
	
	#CPU
	read cpu a b c idle rest < /proc/stat
	total=$((a+b+c+idle))
	intervaltotal=$((total-prevtotal))
	(( prevtotal != 0 )) && CPU=$((100* ( intervaltotal - (idle - previdle) ) / intervaltotal)) || CPU=0
	prevtotal=$total
	previdle=$idle
	
	#MEM
	while read type size kb; do
		[[ $type == MemTotal: ]] && total=$size && used=$total
#		[[ $type =~ (MemFree|Buffers|Cached): ]] && ((used-=size))
		[[ $type == MemFree: ]] && ((used-=size))
		[[ $type == Buffers: ]] && ((used-=size))
		[[ $type == Cached: ]] && ((used-=size))
	done < /proc/meminfo
	MEM=$(( (100 * used) / total))
}

function updatedata_perminute() {
	TIMERS=$(ps -o cmd,etime -p $(pgrep sleep || echo 1) | grep 'sleep [0-9]*[mh]' | sed 's/.* \([0-9]*[hm]\)   *\(.*\)/\2\t\1/g')
	LOWHD=$(df -HP | sed -rn '/(97|98|99|100)%/{s/.* //; H}; ${x; s///; s// /g;p}')
	USATZ=$(TZ=America/New_York date +"%H:%M")
	TIME=$(date +"%H:%M")
	JPTZ=$(TZ=Asia/Tokyo date +"%H:%M")
	DATE=$(date +"%a %b%d %Y")
	DAYNR=$(date +%w)
}

counter=-1

while true; do
	new_lines=$(tput lines)
	new_cols=$(tput cols)
	(( new_lines != old_lines || new_cols != old_cols )) && clear
	old_lines=$new_lines
	old_cols=$new_cols

	updatedata_persecond
	((counter++ % 10 == 0)) && {
		updatedata_perminute
		[[ $oldLOWHD != ${#LOWHD} || $oldTIMERS != ${#TIMERS} ]] && clear
		oldLOWHD=${#LOWHD}
		oldTIMERS=${#TIMERS}
		[[ $oldDAYNR != $DAYNR ]] && kanji_background
		oldDAYNR=$DAYNR
	}

	for id in CPU MEM DOWN UP TEMP; do
		eval $id'log=( $'$id' ${'$id'log[@]:0:59} )'
		eval 'lohi ${'$id'log[@]}'
		eval $id'lo='$LO
		eval $id'hi='$HI
	done

	echo -ne '\e[0;0H'
	{
	printf "%5.5s│%5.5s│%5.5s│%5.5s\n" \
		DATE $DATE \
		TZ $USATZ $TIME $JPTZ
	
	echo '─────┼─────┼─────┼─────'
	printf "%5.5s│%5.5s│%5.5s│%5.5s\n" \
		CPU $CPU $CPUlo $CPUhi \
		MEM $MEM $MEMlo $MEMhi \
		DOWN $DOWN $DOWNlo $DOWNhi \
		UP $UP $UPlo $UPhi \
		TEMP $TEMP $TEMPlo $TEMPhi
	
	echo '─────┼─────┼─────┼─────'
	IFS=$'\n'
	printf "%5.5s│%5.5s│%5.5s│%5.5s\n" \
		LOWHD $LOWHD $(for unused in $(seq $((3 - $(echo "$LOWHD" | wc -w) ))); do echo ' '; done) \
		TIMERS $TIMERS $(for unused in $(seq $((3 - $(echo "$TIMERS" | wc -w) )) ); do echo ' '; done)
	} | sed "$DAYTOTAL"
	IFS=$'\n\t '
	sleep 0.$(( 1000000000 - $(date +%-N) ))s
done

Last edited by Procyon (2011-08-25 00:47:20)

Offline

#1535 2011-08-25 06:49:53

iTwenty
Member
From: India
Registered: 2010-10-24
Posts: 63
Website

Re: Post your handy self made command line utilities

A script to launch your GTK bookmarks in Thunar using dmenu:

#! /usr/bin/env zsh
FILE="$HOME/.gtk-bookmarks"
LIST=`cat $FILE` 
CHOICE=`echo $LIST | cut -d" " -f2- | dmenu -b -i -fn '-*-tamsyn-medium-*-*-*-17-*-*-*-*-*-iso8859-1'`
if [ "x$CHOICE" != "x" ]; then
    URI=`echo $LIST | grep $CHOICE | cut -d" " -f1`
    exec Thunar $URI & disown
fi

Caveats:
>> Your bookmarks must all have a name. In Thunar, right click the bookmark and select "Rename Shortcut"
>> Does not work in bash tongue For some reason, bash insists on converting the newline characters to spaces when I do cat $FILE.

Last edited by iTwenty (2011-08-25 06:53:48)


“Twenty years from now you will be more disappointed by the things that you didn't do than by the ones you did do. So throw off the bowlines. Sail away from the safe harbor. Catch the trade winds in your sails. Explore. Dream. Discover.” - Mark Twain

Offline

#1536 2011-08-25 10:10:50

falconindy
Developer
From: New York, USA
Registered: 2009-10-22
Posts: 4,111
Website

Re: Post your handy self made command line utilities

iTwenty wrote:

>> Does not work in bash tongue For some reason, bash insists on converting the newline characters to spaces when I do cat $FILE.

Unrelated to the assignment... It's because "$LIST" and $LIST are 2 very different things when passed to echo.

Offline

#1537 2011-08-27 08:09:23

Nisstyre56
Member
From: Canada
Registered: 2010-03-25
Posts: 85

Re: Post your handy self made command line utilities

Was playing around with Pygments and made this code pasting tool. It supports every language that Pygments does, which is quite a few.

#!  /usr/bin/env python2

from urllib2 import urlopen
from urllib import urlencode
from sys import argv as args

codefile, language = args[1:]

with open(codefile) as code:
    code = code.read()

data = urlencode({"code" : code, "language" : language})

print urlopen("http://infocalypse-net.info:81/paste", data).read()

e.g.

http://infocalypse-net.info:81/view?pas … 16a100289c

Last edited by Nisstyre56 (2011-08-27 08:09:54)


In Zen they say: If something is boring after two minutes, try it for four. If still boring, try it for eight, sixteen, thirty-two, and so on. Eventually one discovers that it's not boring at all but very interesting.
~ John Cage

Offline

#1538 2011-08-27 18:15:56

owain
Member
Registered: 2009-08-24
Posts: 251

Re: Post your handy self made command line utilities

iTwenty wrote:

A script to launch your GTK bookmarks in Thunar using dmenu:

#! /usr/bin/env zsh
FILE="$HOME/.gtk-bookmarks"
LIST=`cat $FILE` 
CHOICE=`echo $LIST | cut -d" " -f2- | dmenu -b -i -fn '-*-tamsyn-medium-*-*-*-17-*-*-*-*-*-iso8859-1'`
if [ "x$CHOICE" != "x" ]; then
    URI=`echo $LIST | grep $CHOICE | cut -d" " -f1`
    exec Thunar $URI & disown
fi

Caveats:
>> Your bookmarks must all have a name. In Thunar, right click the bookmark and select "Rename Shortcut"
>> Does not work in bash tongue For some reason, bash insists on converting the newline characters to spaces when I do cat $FILE.

This one-liner seems to work in Bash:

thunar $(grep " $(cat $HOME/.gtk-bookmarks | cut -d' ' -f2- | dmenu -b -i)" $HOME/.gtk-bookmarks | cut -d' ' -f1 | head -n 1)

Using egrep to avoid matching the uri rather than keywords, and taking only the first line in case of (a) multiple matches or (b) dmenu exiting without a result, in which case all results match the grepping for a single space.

Offline

#1539 2011-08-28 03:21:55

Jelle
Member
From: Netherlands
Registered: 2011-01-30
Posts: 84

Re: Post your handy self made command line utilities

A quick (but functional) hack of two scripts to batch resample super high-res flac files to a somewhat lower resolution (my network player only goes up to 24bit/96khz).

#!/bin/bash

### replace whitespaces with underscores ###

for i in *.flac; do
	if [ "$i" != `echo "$i"| sed 's/ /\_/g'` ]; then
		mv "$i" `echo "$i"| sed 's/ /\_/g'`
	elif [ "$i" == `echo "$i"| sed 's/ /\_/g'` ]; then
		echo "file does not contain whitespaces"
	else
		echo "Unknown filename error"
	fi
done

### convert 176.400kHz to 88.200 or 192.000kHz to 96.000 ###

for i in *.flac; do
	if [ `metaflac --show-sample-rate $i` == "176400" ]; then
		echo "Resampling to 88.200kHz..."
		sox "$i" `echo "$i"| sed 's/.flac/88.2.flac/g'` rate -v 88200
	elif [ `metaflac --show-sample-rate $i` == "192000" ]; then
		echo "Resampling to 96.000kHz..."
		sox "$i" `echo "$i"| sed 's/.flac/96.flac/g'` rate -v 96000
	elif [ `metaflac --show-sample-rate $i` == "88200" ]; then
		echo "File already in 88.200kHz"
	elif [ `metaflac --show-sample-rate $i` == "96000" ]; then
		echo "File already in 96.000kHz"
	else
		echo "Unknown conversion error"
	fi
	echo "Done!"
done

Offline

#1540 2011-08-28 05:14:41

steabert
Member
Registered: 2011-04-18
Posts: 78

Re: Post your handy self made command line utilities

You could make use of rename or perl-rename and the case statement:

#!/bin/bash

### replace whitespaces with underscores ###

for i in *.flac; do perl-rename 's/ /_/g' $i; done

### convert 176.400kHz to 88.200 or 192.000kHz to 96.000 ###

for i in *.flac; do
	sample_rate=$(metaflac --show-sample-rate $i)
        case $sample_rate in
        176400)
		echo "Resampling to 88.200kHz..."
		sox "$i" ${i%.flac}-88.2.flac rate -v 88200 ;;
	192000)
		...
        esac
done

Offline

#1541 2011-08-28 07:02:03

doorknob60
Member
Registered: 2008-09-29
Posts: 403

Re: Post your handy self made command line utilities

Play a youtube video directly with mplayer (requires youtube-dl). Thanks to metalx1000 for this one though, he had a video tutoial basically showing how to do this smile

#!/bin/sh
RAWURL=`youtube-dl -g --cookies /tmp/ytdl-cookie.txt "$1"`
mplayer -cookies -cookies-file /tmp/ytdl-cookie.txt "$RAWURL"
rm /tmp/ytdl-cookie.txt

Another version that grabs the original URL from the clipboard and directly plays that (useful for setting to a keyboard hotkey or something):

#!/bin/sh
URL=`xclip -o`
RAWURL=`youtube-dl -g --cookies /tmp/ytdl-cookie.txt "$URL"`
mplayer -cookies -cookies-file /tmp/ytdl-cookie.txt "$RAWURL"
rm /tmp/ytdl-cookie.txt

It is possible to use this with Smplayer or something if you want, but you'll have to go into Smplayer's options and add "-cookies -cookies-file /tmp/ytdl-cookie.txt" to the mplayer paramaters or it won't work. It doesn't mess up playing normal videos so it's fine, but I can't find a way to let Smplayer allow those options from the command line sad It's a thing about Youtube's site using cookies to only allow browsers to access the video, so you have to trick Youtubue into thinking Mplayer is a browser, that's why you need the cookies file.

Offline

#1542 2011-08-28 23:47:21

steelneck
Member
Registered: 2011-08-26
Posts: 57

Re: Post your handy self made command line utilities

Here is a script for scaling all images in a dir and aply a USM sharpening according to chosen size and resolution. I mainly use it to scale down photos i send to a photo lab for printing.

#!/bin/bash 
#
#*** Input ***
#
echo "Chose resolution in Points Per Inch:"
read PPI
echo "Chose image height in mm:"
read MM 
#
#*** Calculate image size ***
#
Ss=`echo "scale=4; $MM / 25.4 * $PPI" | bc`
Si=`echo $Ss | sed 's/\..*//'`
#
#*** Calculate USM Radius and Sigma ***
#
USMr=`echo "scale=1; $PPI / 160" | bc | sed 's/^\./0\./'`
if [ "$USMr" \> 1 ] 
then
USMs=`echo "scale=1; sqrt($USMr)" | bc | sed 's/^\./0\./'`
else
USMs=$USMr
fi
#
#*** Scale images ***
#
echo 'Scaling pictures....'
#
LIST=`ls | grep ".jpg\|.tif\|.ppm\|.pnm"`
for i in $LIST; do
  GEO_B=$(identify "$i" | awk '{print $3}' | awk -F x '{print $1}')
  GEO_H=$(identify "$i" | awk '{print $3}' | awk -F x '{print $2}')
  if [[ $GEO_B > $GEO_H ]] 
  then 
    DIM="x$Si"
  else 
    DIM="$Si"
  fi
  u=${i%.*}.jpg
  convert $i -strip -filter Lanczos -resize "$DIM" -density "$PPI"x"$PPI" \
  -unsharp "$USMr"x"$USMs"+0.8+0.03 -type TrueColor -quality 96 $u
  echo "$i --- klar"
done
TB=`ls | grep ".tif\|.ppm\|.pnm"`
for i in $TB; do
  rm $i
done
#
#*** Make a "contact sheet" ***
#
montage -label '%f' -size 140x360 '*.jpg[120x180]' -tile 6 -quality 80 directory.jpg

Offline

#1543 2011-08-29 00:02:26

steelneck
Member
Registered: 2011-08-26
Posts: 57

Re: Post your handy self made command line utilities

A little script to do withoutdisplay managers, put last in your .profile, .bash_profile or whatever file you use for those things you want done upon login

RLVL=$(who -r | awk '{print $2}')
if [ $RLVL = 5 ]; then
  if [ ! -e /tmp/.X0-lock ]; then
    startx
    exit
  fi
fi

Then set your runlevel to 5 in /etc/inittab and comment out the login manager line. Viola!

Offline

#1544 2011-08-31 03:45:05

moetunes
Member
From: A comfortable couch
Registered: 2010-10-09
Posts: 1,033

Re: Post your handy self made command line utilities

I've been using mplayer as a command line music player but it spews out alot of useless(to me) info...
So eventually I've managed to come up with this

 mplayer -ao alsa -shuffle -playlist ~/Favs/playlist.txt | tee >(grep Title >&2) | (grep Artist)

to get the output to be

 Title: Wild Wild Life
 Artist: Talking Heads

Cheers


You're just jealous because the voices only talk to me.

Offline

#1545 2011-08-31 05:06:35

lolilolicon
Member
Registered: 2009-03-05
Posts: 1,722

Re: Post your handy self made command line utilities

@moetunes, Why do you use process substitution and subshell here at all? You could just do

mplayer ... | grep '^[[:space:]]*\(Title\|Artist\):'

unless for some reason you want to put "Title" to stderr while "Artist" stdout... even so the (grep Artist) subshell is still redundant.

[Edit]
(Alternatively, in a "I see what you did there" tone)
Clever, but don't miss the straight forward way to do it <insert code above> ... big_smile

Last edited by lolilolicon (2011-08-31 05:16:33)


This silver ladybug at line 28...

Offline

#1546 2011-08-31 05:46:40

moetunes
Member
From: A comfortable couch
Registered: 2010-10-09
Posts: 1,033

Re: Post your handy self made command line utilities

I did make that hard for myself...
Now I'm using:

mplayer -ao alsa -shuffle -playlist ~/Favs/playlist.txt | egrep "Title|Artist"

I remembered grep -e when I was having a tub after posting... wink


You're just jealous because the voices only talk to me.

Offline

#1547 2011-08-31 08:45:25

Jelle
Member
From: Netherlands
Registered: 2011-01-30
Posts: 84

Re: Post your handy self made command line utilities

Ok, inspired by Steabert, first round of cleanup (and some added stuff).

#!/bin/bash

### replace whitespaces with underscores ###

for i in *.flac; do
	if [ "$i" != `echo "$i"| sed 's/ /\_/g'` ]; then
		mv "$i" `echo "$i"| sed 's/ /\_/g'`
	elif [ "$i" == `echo "$i"| sed 's/ /\_/g'` ]; then
		echo "file does not contain whitespaces"
	else
		echo "Unknown filename error"
	fi
done

### convert 176.400kHz to 88.200 or 192.000kHz to 96.000 ###

for i in *.flac; do
	sample_rate=$(metaflac --show-sample-rate $i)
        case $sample_rate in
        176400)
		echo "Resampling to 88.200kHz..."
		sox -S -G "$i" ${i%.flac}-88.2.flac rate -v 88200
		mv $i ~/downloads/TM/processed/
		metaflac --remove-tag=description ${i%.flac}-88.2.flac; metaflac --remove-tag=comment ${i%.flac}-88.2.flac
		metaflac --set-tag="description=24/176.400khz to 24/88.2khz with sox" ${i%.flac}-88.2.flac ;;
	192000)
		echo "Resampling to 96.000kHz..."
		sox -S -G "$i" ${i%.flac}-96.flac rate -v 96000
		mv $i ~/downloads/TM/processed/
		metaflac --remove-tag=description ${i%.flac}-96.flac; metaflac --remove-tag=comment ${i%.flac}-96.flac
		metaflac --set-tag="description=24/192khz to 24/96khz with sox" ${i%.flac}-96.flac ;;
	88200)
		echo "File already 24bit/88.200kHz" ;;
	96000)
		echo "File already 24bit/96.000kHz" ;;
        esac
done

Next up: no longer needing to cd into the directory with hi-res files.

Offline

#1548 2011-08-31 21:35:26

moetunes
Member
From: A comfortable couch
Registered: 2010-10-09
Posts: 1,033

Re: Post your handy self made command line utilities

Instead of editing ~/.gtkrc-2.0 directly I whipped up an xmessage window that'll let me select a theme with a button click big_smile

#!/bin/bash

# List the folders in ~/.themes on xmessage buttons
# for easy selection and edit the ~/.gtkrc-2.0 file accordingly

# find out the current theme
current=`grep include ~/.gtkrc-2.0 | cut -d "/" -f5`
a=1
## set it up so there are the right num buttons and they have the right label
## "Aspares" is a folder I made to store things I don't want to show up
for f in `ls -I Aspares ~/.themes/`; do
	[ "$a" = "1" ] && butlabel="$f:0" || \
		butlabel="$butlabel,$f:0"
	((a++))
done

this_theme=`xmessage -center -print -buttons $butlabel "The current theme is : $current   "`
[ "$this_theme" != "" ] && sed -i "s/$current/$this_theme/" ~/.gtkrc-2.0
newtheme=`grep include ~/.gtkrc-2.0 | cut -d "/" -f5`
xmessage -timeout 2 -center "GTK Theme is now: $newtheme   "

exit 0

Cheers


You're just jealous because the voices only talk to me.

Offline

#1549 2011-09-03 14:40:09

bloom
Member
Registered: 2010-08-18
Posts: 749
Website

Re: Post your handy self made command line utilities

Here's a2l, an aria2mon replacement (which doesn't crash on non utf-8 chars):

#! /usr/bin/env python2

import urllib2, json

MAX_NAME_LEN = 50
ELLIPSIS = "..."

def abbrev (value):
  n = value / 1024.0
  if n < 1:
    return "%dB" % value
  value = n
  n = value / 1024.0
  if n < 1:
    return "%.1fK" % value
  else:
    value = n;
    n = value / 1024.0
    if n < 1:
        return "%.1fM" % value
    else:
        return "%.1fG" % n

def arrival (downloadSpeed, remainingLength):
    if (downloadSpeed == 0): return "n/a"
    s = remainingLength / downloadSpeed
    h = s / 3600
    s = s % 3600
    m = s / 60
    s = s % 60
    result = ""
    if (h > 0): result += "%dh" % h
    if (m > 0): result += "%dm" % m
    result += "%ds" % s
    return result

def main():
    jsonreq = json.dumps({'id':'foo', 'method':'aria2.tellActive'})
    c = urllib2.urlopen('http://localhost:6800/jsonrpc', jsonreq)
    response = json.loads(c.read())
    for r in response['result']:
        completed = float(r['completedLength'])
        total = float(r['totalLength'])
        remainingLength = total - completed
        downloadSpeed = float(r['downloadSpeed'])
        eta = arrival(downloadSpeed, remainingLength)
        percent = -1;
        if (total > 0): percent = 100 * completed / total
        else: percent = 100
        dl = downloadSpeed / 1024;
        ul = float(r['uploadSpeed']) / 1024;
        name = r['bittorrent']['info']['name']
        if len(name) > MAX_NAME_LEN: name = name[:MAX_NAME_LEN - len(ELLIPSIS)] + ELLIPSIS
        print "%3s %-50s\t%.1f%%\t%s\t%.1f\t%.1f\t%s/%s\t%s" % (r['gid'], name, percent, abbrev(total), dl, ul, r['numSeeders'], r['connections'], eta)

if __name__ == "__main__":
    main()

Last edited by bloom (2011-09-05 12:31:18)


gh · da · ds

Offline

#1550 2011-09-06 07:14:00

doorknob60
Member
Registered: 2008-09-29
Posts: 403

Re: Post your handy self made command line utilities

I'm sure the way it's currently constructed, it's not super useful, but it could be modified to become useful. Basically, I downloaded a bunch of FLV files (with youtube-dl), and they are all in 16:9 format, but the original source should have been in 4:3 (I hate when people stretch their vids before uploading to Youtube....grr...). This script takes the 16:9 FLV files, and converts them all into MKV files with the correct 4:3 aspect, all without the need for reencoding, so it does it quickly, and with no quality loss (MKV because it's the container that seems to work best without reencoding), and also backs up the FLV files, just in case. I'm sure some parts of this could potentially be handy for some people smile

(requires ffmpeg and mkvtoolnix)

#!/bin/bash
for i in `ls *.flv`; do
		name=`echo "$i"|sed 's/.flv//'`
		ffmpeg -i "$i" -vcodec copy -acodec copy "${name}-pre.mkv"
		mkvmerge -o "${name}.mkv" --aspect-ratio "1:4/3" "${name}-pre.mkv"
		rm "${name}-pre.mkv"
		mv "$i" flv-backup/
done

Last edited by doorknob60 (2011-09-06 07:14:13)

Offline

Board footer

Powered by FluxBB