r/ScriptSwap • • May 31 '17

[Batch] Computer part info gathering (Nothing fancy)

7 Upvotes

I was just put on a project where I needed to get the computer part information from all of our clients computers. (Motherboard model, network config, memory info, etc.) So I made a quick program that brought up all the information for me using the wmic command (learn it, it makes life easy) then once the project was done expanded it a little to add some menu options just for fun. I'll probably add a custom option soon.

Find it here: https://pastebin.com/ugLAmMX7


r/ScriptSwap • • Feb 25 '17

[sh] Programme Reminder

7 Upvotes

http://pastebin.com/9AuQDjtc

Example 'notifyprogrammesdata' document: https://i.gyazo.com/e04c4b8294011663ae6640a09d1ae1e9.png

It shows if there's a programme available on that day. Sure it could be better as to show all of the programmes you've not been notified of (if that's even possible?) but it's good for me cause I boot up my computer daily anywho.

I don't use it in cron daily, but I probably will eventually.

Anywho, enjoy, someone will maybe lol


r/ScriptSwap • • Jan 31 '17

[first project] Sync and manage your todoist task list from the terminal

7 Upvotes

r/ScriptSwap • • Aug 10 '16

CMus tmux script

7 Upvotes

I wrote a short script that allows me to start cmus in a tmux session and reconnect to it easily. If there is already a session called cmus, it attaches to that. Otherwise it creates a new session without a status bar.

#!/bin/bash

TMUX_BINARY="$(which tmux)"
TMUX_SESSION_NAME="cmus"

if ! tmux has-session -t "${TMUX_SESSION_NAME}" > /dev/null 2>&1; then
  tmux new-session -d -s "${TMUX_SESSION_NAME}" cmus
  tmux set-option -t "${TMUX_SESSION_NAME}" status off
fi

tmux attach-session -t "${TMUX_SESSION_NAME}"

Gist

I named mine cmux and aliased it to cmus too, so I can just do this;

$ cmus
[cmus is opened full screen]
PREFIX + D
[disconnected but cmus is still playing]
$ cmus
[same cmus session is reopened]

r/ScriptSwap • • Mar 25 '16

Looking for a script that displays /r/jokes with setup and punchline on one page. (so you don't have to click to see the punchline)

7 Upvotes

r/ScriptSwap • • Mar 10 '16

Has anyone here written a script that localy runs on your firefox browser that lets you enter something like reddit:webdev and it takes you there?

7 Upvotes

Thanks


r/ScriptSwap • • Oct 30 '15

[bash] Download videos from subreddit

7 Upvotes

This downloads videos from some sites from subreddits using youtube-dl. If you find a bug please leave a comment. This use the .json version of the subreddit https://www.reddit.com/r/ScriptSwap/.json

     #!/bin/bash
# video_down.sh
# be sure to use the .json when you add a subreddit (https://www.reddit.com/r/vids/.json) or this wil likely fail
#!/bin/bash
#video_down.sh
# Version 1.1 I fixed a bad grep that lead to youtube-dl erroring out
# urls is the urls you want to watch for links. Be sure to use the .json of the reddit (reddit.com/r/vids.json)
urls=(  )
# sites is the site you want video links from youtube.com ect. DO NOT add http or www. before the site
sites=( )
now=$(date +%Y_%m_%d)
curl "${urls}" >> /tmp/video_links.txt
egrep  -o "\"url\": \"(http(s)?://){1}[^'\"]+" /tmp/video_links.txt > /tmp/video_links2.txt 
for i in "${sites[@]}"
do
grep "$i" /tmp/video_links2.txt >> /tmp/video_links3.txt
done
sed -i 's/"url": "/ /g' /tmp/video_links3.txt
#awk '{ for (i=1;i<=NF;i++) print $i }' /tmp/video_links3.txt
sort /tmp/video_links3.txt | uniq > /tmp/video_links4.txt
cd ~/Downloads/porn
mkdir $now
cd ~/Downloads/porn/$now
youtube-dl -a /tmp/video_links4.txt
cd /tmp
rm video_links*

r/ScriptSwap • • Oct 11 '15

[BASH] Flashdrive essential program downloader

7 Upvotes

https://github.com/braeden123/Flashdrive-Updater/blob/master/update.sh

The script creates some folders in the current dir and automates the download of

  • Ccleaner

  • Malwarebytes

  • Chrome x64

  • Sublime Text 2

I will add more in the future and am open to suggestions -- I commented out rkill and combo fix since they both use 2-3 use tokens in their URLs.

Please leave any feedback/suggestions that you have, thanks!


r/ScriptSwap • • Sep 13 '15

[PYTHON] Script to download images you've saved or upvoted on reddit (Github)

7 Upvotes

I whipped up this script in an hour that uses PRAW to get all posts you've upvoted or saved on reddit, then downloads all images using urllib.

It's extremely rough, but it gets the job done.

Get the script from Github!


r/ScriptSwap • • Jan 11 '15

[sh] Watch porn on Linux using FF + mplayer

7 Upvotes

Start a few isolated FF instances (note: install Adblock in each profile!):

#!/bin/sh
for i in 1 2 3; do
  firefox -private -no-remote -profile ~/.private_profiles/p$i &
done

Find some (ugh) Flash videos, and let them buffer. Drag & drop the links to the isolated profiles, or else the single, monolithic Flash plugin instance is likely to crash and kill all the buffers.

Enjoy your videos in a dedicated media player:

#!/bin/sh
find $(for i in `pgrep "contain"` ; do
  ls -1d /proc/$i/fd
done) -size 1M \
| xargs file -iL \
| sed -n 's/^\([^:]*\): *video\/.*/\1/p' \
| xargs  mplayer -forceidx -fs "$@"

r/ScriptSwap • • Jan 06 '15

[Batch] Display the size of all of your disks (not partitions; disks)

7 Upvotes

This batch file creates and runs a helper script in VBS, which is kludgy. I'd like to see the whole thing re-written in PowerShell. Other than that, I think it's a useful batch file.

Per the sidebar rules, I will include a license: the MIT License

@ECHO OFF
CLS
SETLOCAL ENABLEDELAYEDEXPANSION

ECHO                             ************************
ECHO                             * PHYSICAL DISK DRIVES *
ECHO                             ************************
ECHO.

IF NOT EXIST "%windir%\system32\wbem\wmic.exe" GOTO WMICNotFound

> "%TEMP%\DiskSizeEval.vbs" ECHO Set objArgs = WScript.Arguments
>>"%TEMP%\DiskSizeEval.vbs" ECHO WScript.Echo Round(eval(objArgs(0)),2)

FOR /F "skip=1 tokens=1-3" %%A IN ('"WMIC DISKDRIVE GET Index,InterfaceType,Size"') DO (
 IF NOT '%%B'=='' (
  SET DiskIndex=%%A
  SET DiskInterfaceType=%%B

  ECHO %%C> "%TEMP%\DiskTotalBytes.txt"
  SET /P DiskTotalBytes=<"%TEMP%\DiskTotalBytes.txt"
  DEL "%TEMP%\DiskTotalBytes.txt"

  FOR /F "skip=1 tokens=1,*" %%D IN ('"WMIC DISKDRIVE WHERE Index=!DiskIndex! GET Index,Model"') DO IF NOT '%%E'=='' SET DiskModel=%%E
  FOR /F %%F IN ('CScript "%TEMP%\DiskSizeEval.vbs" //Nologo !DiskTotalBytes!/1000/1000/1000') DO SET DiskTotalGB=%%F
  FOR /F %%F IN ('CScript "%TEMP%\DiskSizeEval.vbs" //Nologo !DiskTotalBytes!/1024/1024/1024') DO SET DiskTotalGiB=%%F

  ECHO Interface Type: !DiskInterfaceType!
  ECHO          Model: !DiskModel!
  ECHO     Total Size: !DiskTotalGB! GB [!DiskTotalGiB! GiB]
  ECHO.
  ECHO           ------------------------------------------------------------
  ECHO.
 )
)

SET DiskInterfaceType=
SET DiskTotalBytes=
SET DiskTotalGB=
SET DiskTotalGiB=
DEL "%TEMP%\DiskSizeEval.vbs"
PAUSE
GOTO EOF

:WMICNotFound
ECHO This batch file cannot continue because the following file wasn't found:
ECHO.
ECHO "%windir%\system32\wbem\wmic.exe"
ECHO.
PAUSE

:EOF

I have some sample output too. I ran this on my desktop computer, which has two internal hard drives (a 1 TB and a 2 TB) and a memory card reader that has four slots (I only had an 8 GB SD card in at the time that I ran the script). Here it is:

                            ************************
                            * PHYSICAL DISK DRIVES *
                            ************************

Interface Type: IDE
         Model: WDC WD1002FAEX-00Z3A0 ATA Device
    Total Size: 1000.2 GB [931.51 GiB]

          ------------------------------------------------------------

Interface Type: IDE
         Model: WDC WD2002FAEX-007BA0 ATA Device
    Total Size: 2000.4 GB [1863.01 GiB]

          ------------------------------------------------------------

Interface Type: USB
         Model: TEAC USB   HS-CF Card USB Device
    Total Size: 0 GB [0 GiB]

          ------------------------------------------------------------

Interface Type: USB
         Model: TEAC USB   HS-MS Card USB Device
    Total Size: 0 GB [0 GiB]

          ------------------------------------------------------------

Interface Type: USB
         Model: TEAC USB   HS-SD Card USB Device
    Total Size: 8 GB [7.45 GiB]

          ------------------------------------------------------------

Interface Type: USB
         Model: TEAC USB   HS-xD/SM USB Device
    Total Size: 0 GB [0 GiB]

          ------------------------------------------------------------

Press any key to continue . . .

r/ScriptSwap • • Aug 22 '14

[Bash] Rip imgur album (while preserving order) with aria2

7 Upvotes

Yeah, there's a download button in every album's sidebar; but that doesn't do parallel downloads and consequently, doesn't quite saturate my connection.

You will need aria2 and bc (for the progress bar).

Usage:

 ./aria2imgur.sh album-name

Example:

./aria2imgur.sh https://imgur.com/a/0KoeX

If you decide to rename the script to something else, make sure you change the filename on line 49.

#!/bin/bash
#Requires aria2, bc

if [ -f .htmltmp ]; then

#Download progress bar
currentdown=$(cat .downprogress)
currentdown=$[ $currentdown +1 ]

percent=$( echo "($(echo "$currentdown/$totaldown * 100" | bc -l )+0.5)/1" | bc )
remaining=$(( 100 - $percent ))

echo -ne "\r["
printf "%0.s=" `seq $percent`
echo -n ">"
[[ $remaining != 0 ]] && printf "%0.s." `seq $remaining`
echo -n "] $percent% ($currentdown/$totaldown files completed)"

echo $currentdown > .downprogress
exit

else	

#Save html source and filename
curl -s $1 >> .htmltmp
url=$1

#Parse html for image links and album title (to create a folder for)
awk -F\" '/data-src/ {print $10}' .htmltmp | sed '/^$/d' | sed 's/s.jpg/.jpg/g' | sed -e 's/^/http:/' >> .htmltmp1
fold=$(awk -F\" '/data-title/ {print $6; exit}' .htmltmp | tr -d ' ')

mkdir $fold 2> /dev/null
#Account for blank titles, already existing directory or incompatible special characters
if [ $? = 1 ]; then
	echo "Error creating directory - defaulting to album url"
	fold=$(echo "${url##*/}")
	mkdir $fold
fi
echo "Saving files to "$(pwd)/$fold

#Data for progress bar
totaldown=$(wc -l .htmltmp1 | awk '{ print $1 }')
export totaldown
echo 0 > .downprogress

#Download generated link file
echo "Downloading files..."
echo
aria2c --dir=$(pwd)/$fold --input-file=$(pwd)/.htmltmp1 -q --on-download-complete ./aria2imgur.sh

#aria2 error status
if [ $? = 0 ]; then
	errors="no download errors"
	else
	errors="download errors"
fi

#Rename files according to album order - aria2 doesn't support this with its -o flag
while read line
	do
	file_counter=$[ $file_counter +1 ] 
	file_name=$(echo "${line##*/}")
	mv $(pwd)/$fold/$file_name $(pwd)/$fold/"$file_counter - $file_name"
done < .htmltmp1

#Remove temporary files
rm  .htmltmp .htmltmp1 .downprogress

echo
echo
echo "Done with" $errors

fi

Note: I put in a progress bar because the aria2 output sucks for readability. Unfortunately, I can't seem to get the data I need for progression by bytes downloaded from aria2. You could get that from another loop but that seems wasteful.

Here's a pastebin link if you're into that sort of thing: http://pastebin.com/YeGfni3N


r/ScriptSwap • • Jun 13 '14

[Bash] android-scrot takes screenshots from android devices by adb and usb and rotates them according the screen orientation

7 Upvotes

As and editor for a couple of magazines I often need to take screenshots of android apps and devices. Pressing volume down+power and transfering the screenshots to a computer (either by file transfer, Google+ oder Dropbox...) takes a lot of time, so i wrote android-scrot.

Thr script establishes a adb connection, executes the screenshot function and loads the picture to your computer. After that android-scrot checks the screen orientation and rotates the screenshot accordingly.

#!/bin/bash
#  android-scrot takes screenshots of a android phone by adb
#  
#  Copyright 2014 Christoph Langner <mail AAATTT christoph-langner.de>
#  
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#  
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#  
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.

## Check for adb and imagemagick
command -v adb >/dev/null 2>&1 || {
	echo >&2 "Please install adb from the android sdk.  Aborting.";
	exit 1;
}

## Start adb server if necessary
if [ ! $(pgrep adb) ]; then
	adb start-server
fi

## Timestamp
TIME=$(date "+%d-%m-%Y_%H-%M-%S")

## Rename file
if [ -z "$1" ]; then
	FILENAME=android_$TIME.png
else
	FILENAME=$1_$TIME.png
fi

## Wait for phone
if [ $(adb get-state) == "unknown" ]; then
	echo Please connect your phone and activate USB-Debugging
	adb wait-for-device
fi

## Take screenshot
adb shell screencap -p | perl -pe 's/\x0D\x0A/\x0A/g' > $FILENAME
echo $FILENAME saved

## Rotate image if imagemagick is installed
command -v mogrify >/dev/null 2>&1 || {
	echo >&2 "Please install imagemagick to rotate images automatically.";
	exit 1;
}
ORIENTATION=$(adb shell dumpsys input | grep 'SurfaceOrientation' | xargs | awk '{ print $2 }')
if [ $(echo $ORIENTATION | grep 1) ]; then
	mogrify -rotate -90 $FILENAME
elif [ $(echo $ORIENTATION | grep 3) ]; then
	mogrify -rotate 90 $FILENAME
elif [ $(echo $ORIENTATION | grep 2) ]; then
	mogrify -rotate 180 $FILENAME
fi

To execute android-scrot you need adb out of the android-sdk (on Arch Linux you can get adb and fastboot out of the AUR package android-sdk-platform-tools) and Imagemagick for the image rotation. Yout can call the script with or without a file name.

$ android-scrot
android_12-02-2014_11-17-43.png saved
$ android-scrot your-app
your-app_12-02-2014_11-18-04.png saved

I used android-scrot on many devices, it should work on yours too. The script is licensed under the GPLv2 and later. For those, who like a decent source dump better, there's a GitHub under https://github.com/linuxundich/android-scrot


r/ScriptSwap • • Jun 08 '14

[BATCH/Windows 7+] Clear All Event Logs

7 Upvotes

In a batch file:-

@echo off
for /f %%x in ('wevtutil el') do wevtutil cl "%%x"

From the command line directly:-

for /f %x in ('wevtutil el') do wevtutil cl "%x"

r/ScriptSwap • • Jun 04 '14

[Bash+Linux] Run a command, then have your DE notify you

7 Upvotes
#!/bin/bash
set -eu

notify() {
 # arguments to Notify(): 
  # app_name, replaces_id, app_icon, summary, body, (actions (?), hints,) 
  # expire_timeout
  dbus-send --dest=org.freedesktop.Notifications \
    /org/freedesktop/Notifications org.freedesktop.Notifications.Notify \
    string:$1 uint32:$2 string:$3 string:$4 string:$5 array:string: array:string: int32:${6--1}
}

# Run command
$* && result="Successful" || result='Failed'

notify "" 0 "" "${result}" "yay"

Runs your script, then sends a dbus message that causes your Desktop Environment to pop up a message telling you it's done. Handy for compiling big things, copying large directories, etc.

Edit: Damn, I was really lazy both when I wrote this, and when I posted it here. I should have explained that to use it you just type notify followed by your command. An example might be notify rsync Music /media/disk/Music. That would sync your rsync directory to /media/disk, and then (presumably like an hour later when you've minimised the terminal, gone on Reddit, and forgotten what the hell you were doing), pop up a notification in your GUI to let you know it's done.

As I've mentioned in the comments, it's not finished as the notification will just say "yay" instead of telling you what has actually happened. If anyone feels like fixing that, it should be pretty simple if you understand Bash better than me. Similarly it would be useful if you could do stuff like notify ( do_something && do_something_else ). I guess eval would probably let you do that.


r/ScriptSwap • • Feb 02 '14

Dogecoin Wallet Update Script

7 Upvotes

I saw some people in /r/dogecoin mentioned that it was difficult to update the Dogecoin client when a new version was released. I wrote up a quick script that will let you choose what version of the wallet you want to use (obtained from https://github.com/dogecoin/dogecoin/releases/). It will back up your wallet.dat, moves your old wallet files, download/extract the new wallet, and puts a link to it on your desktop:

https://dl.dropboxusercontent.com/u/15125541/DogecoinUpdate.zip

You only need to extract the zip onto your computer somewhere, then run DogecoinUpdate.bat. Any time a new wallet is released, you only need to run that .bat file, and it should be able to download the latest version of the wallet. All important files will be located in a new directory, C:\Doge.

Obviously, this is not an official release, and I'm in no way associated with the actual client. I use this on my systems at home, and I thought it might be useful to others as well. Let me know if you have any suggestions!


r/ScriptSwap • • Nov 18 '12

A few scripts that work together to make Synergy dynamically update depending on your workstation

7 Upvotes

For those of us who bounce between workstations a lot, I wrote this, which automatically pulls the most recent UNIX workstation you have logged into/run synergy-server from, and launches it on your Windows laptop. Its pretty specific, but I hope it can save someone else from wasting an hour of their life. The only caveat is that there needs to be some sort of way to pull the $UNIX_NAME from the config file, but that is up to your office's naming conventions.

ON UNIX:

cat .scripts/makeSynergyConf.sh

echo "section: screens

$HOSTNAME:

LAPTOP_NAME:

end

section: links

$HOSTNAME:

left = LAPTOP_NAME

LAPTOP_NAME:

right = $HOSTNAME

end" >~/dynamicSynergy.conf

synergys --config dynamicSynergy.conf


ON Windows:

make a bat file like this:

cd C:"Program Files"\Synergy

findstr "$UNIX_NAME" Z:\dynamicSynergy.conf >mostRecentHostname.txt

set /p mostRECENT=<mostRecentHostname.txt

synergyc.exe %mostRECENT%24800


r/ScriptSwap • • Nov 15 '12

[PERL] Automatic Connection to Synergy Server Depending on your Location (work|home)

7 Upvotes

auto-synergy-loc.pl

Here's a little script I put together for my Mac laptop to connect to my desktop. I run synergy at home and at work and it's kinda a pain to stop/restart with different options depending on where I am. So what this does is check the current wireless SSID I'm connected to and then stop/restart the synergy client, with the correct options, based on the SSID.

It's not pretty but it works. It currently uses the Mac's 'airport' utility to figure out the currently associated SSID but it should be pretty easy to change to use something on Linux or whatever.

Hope you like it and its helpful for you!


r/ScriptSwap • • Oct 24 '12

[Python] Quotarama: the product of a bored afternoon and a healthy love of Futurama.

7 Upvotes

I've just found this subreddit, and thought I'd break the ice here with this offering:

https://github.com/simick/Quotarama

It's a script I wrote to print a random Futurama quote from an XML list, originally inspired by the ones that used to be hidden in the Slashdot HTTP headers, which I now use as my SSH login script. Feel free to add more quotes!


r/ScriptSwap • • Mar 29 '12

[Bash] Mass remove passwords from pdf files

7 Upvotes

Creates a new file for each pdf prefixed with nopw_:

for i in *.pdf; do qpdf --password=PASS --decrypt "$i" "nopw_$i"; done


r/ScriptSwap • • Mar 09 '12

Rule List: what is "very large" source?

7 Upvotes

The wording as it stands is ambiguous, and I'm all ears on how to refine this. I'm just one mod voice here, but I'd define "very large" as > 25 lines. Semi-related: at the end of the day, some people just need syntax coloring to parse code, period. That being said, the end-goal isn't to have this sub full of pastebin links. The thought of linking to pastebin for a one-liner makes me cringe. Thoughts?


r/ScriptSwap • • Mar 08 '12

[Perl] pretty print xml

7 Upvotes

ppxml: Pretty prints XML-ish data even if it is embedded within other data (e.g. log files). I'm sure many people have written something similar. Here's mine. git

#!/usr/bin/perl -w

# xml pretty printer, intended to consume xml within log files. 
#
# input: 2012-03-07 lorem ipsum data=<foo><bar>baz</bar></foo> and yadda=<bip><bop>boop</bop></bip>
#
# output:
# 2012-03-07 lorem ipsum data=
# <foo>
#     <bar>baz</bar>
# </foo>
# and yadda=
# <bip>
#     <bop>boop</bop>
# </bip>
#
# with optional arg --tags-on-own-line it will put every tag on its own line.
#
# 2012-03-07 lorem ipsum data=
# <foo>
#     <bar>
#         baz
#     </bar>
# </foo>
# and yadda=
# <bip>
#     <bop>
#         boop
#     </bop>
# </bip>
#
# In general it is NOT right to parse xml yourself.  There are plenty of libraries for it.
# But I wanted something which would handle partial, malformed and multiple xml sections within log files with really long lines

use strict;
use Data::Dumper;
use Getopt::Long;

my $STATES = {
    EOF => 1,
    LOOKING_FOR_LT => 2,
    LOOKING_FOR_END_OF_CDATA => 3,
    LOOKING_FOR_END_OF_COMMENT => 4,
    LOOKING_FOR_END_OF_TAG => 5,
};

my $TOKENS = {
    non_tag_data => 1,
    cdata => 2,
    comment => 3,
    tag => 4,
};

my $COMPACT = 1;

sub init {
    my $tags_on_own_line;
    GetOptions( "tags-on-own-line", \$tags_on_own_line);
    $COMPACT = !$tags_on_own_line;
}

sub fill_buf {
    my ($state, $ref_indent_level) = @_;

    # The current data being worked upon is stored in $state->{buf} as a string.
    # most of the code in this script removes the first part of that string.
    # e.g.  $state->{buf} =~ s/^some_reg_ex_to_find_an_xml_tag_start//;
    # When the input contains very long lines, we end up truncating/copying the very long line $state->{buf} many times.
    # To speed things up we work on shorter strings.
    # When a line is over $CUT_SIZE characters long, we split it up.
    # We store the split sections in an array ref at $state->{read_ahead}
    # This function is used to handle all that crazy logic.
    # so you eventually end up with $state->{buf} filled with data to work on.
    
    return undef if $state->{state} == $STATES->{EOF};

    while ( (not defined $state->{buf}) ) {
        if ( (defined $state->{read_ahead}) && ( @{$state->{read_ahead}} >= 1 ) ) {
            $state->{buf} = shift @{$state->{read_ahead}};
            next;
        }

        my $line = <>;
        if ( not defined $line ) {
            delete $state->{buf};
            $state->{state} = $STATES->{EOF};
            last;
        }
        chomp $line;

        # Heuristic to reset indent level in log files if we've come across bad data.
        # Generally not needed but YMMV.
        ${$ref_indent_level} = 0 if ( ${$ref_indent_level} > 20
            && $line =~ /^.?(?:\d\d\d\d-\d\d-\d\d |(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [ \d]\d )/ );

        my (@cuts, $at);
        my $CUT_SIZE = 256;

        while( length($line) > $CUT_SIZE && ( -1 != ($at = index($line, '>', $CUT_SIZE)) ) ) {
            push @cuts, substr( $line, 0, $at+1,  '' );
        }
        if ( @cuts ) {
            push @cuts, $line;
            $line = shift @cuts;
            $state->{read_ahead} = \@cuts;
        }
        $state->{buf} = $line;
    }
}
    
sub find_a_token {
    my ($state, $ref_indent_level) = @_;

    my @lines; # we keep reading lines until we can return a token.

    fill_buf( $state, $ref_indent_level );
    return undef if ( not defined $state->{buf} );

    while ( $state->{state} == $STATES->{LOOKING_FOR_LT} ) {

        # We are looking for <
        # So we return all data (dropping whitespace) until we see a <
        # If the first non white space we see is < then we transition to the state which handles <

        # As long as we have no data, get some
        delete $state->{buf} if ( (defined $state->{buf}) && $state->{buf} =~ /^\s*$/ );

        while( not defined $state->{buf} ) {
            fill_buf( $state, $ref_indent_level );
            if ( not defined $state->{buf} ) { # no more data.
                $state->{state} = $STATES->{EOF};
                if ( @lines ) { # we have partial data, so return it.
                    return {
                        token => $TOKENS->{non_tag_data},
                        lines => \@lines,
                    };
                }
                return undef;
            }
            delete $state->{buf} if $state->{buf} =~ /^\s*$/;
        }
        $state->{buf} =~ s/^\s+//;

        # Finally, non white space. If it doesn start with < then it's non_tag_data

        if ( $state->{buf} =~ /^([^<]+)(<.*)?$/ ) {
            push @lines, $1;
            if ( defined($2) ) {
                $state->{buf} = $2;
                return {
                    token => $TOKENS->{non_tag_data},
                    lines => \@lines,
                };
            }
            delete $state->{buf};
            next;
        }

        # found <, but if we saw anything before the < then the old data (in @lines)
        # is the non_tag_data token we should return.

        if ( @lines ) { # we have partial data, so return it.
            return {
                token => $TOKENS->{non_tag_data},
                lines => \@lines,
            };
        }

        # found < so lets get busy

        if ( $state->{buf} =~ /^(<!\[CDATA\[)(.*)$/ ) {
            push @lines, $1;
            if ( defined($2) ) {
                my $rest = $2;
                if ( $rest =~ /^(.*?)(]]>)(.*)$/ ) {
                    $lines[-1] .= $1 . $2;
                    $state->{buf} = $3;
                    $state->{state} = $STATES->{LOOKING_FOR_LT};
                    return {
                        token => $TOKENS->{cdata},
                        lines => \@lines,
                    };
                }
                $lines[-1] .= $rest;
            }
            delete $state->{buf};
            $state->{state} = $STATES->{LOOKING_FOR_END_OF_CDATA};

        } elsif ( $state->{buf} =~ /^(<!--)(.*)$/ ) {

            push @lines, $1;
            if ( defined($2) ) {
                my $rest = $2;
                if ( $rest =~ /^(.*?)(-->)(.*)?$/ ) {
                    $lines[-1] .= $1 . $2;
                    $state->{buf} = $3;
                    $state->{state} = $STATES->{LOOKING_FOR_LT};
                    return {
                        token => $TOKENS->{comment},
                        lines => \@lines,
                    };
                }
                $lines[-1] .= $rest;
            }
            delete $state->{buf};
            $state->{state} = $STATES->{LOOKING_FOR_END_OF_COMMENT};

        } elsif ( $state->{buf} =~ /^(<[^>]*)(>)?(.*)?$/ ) {

            push @lines, $1;
            $lines[-1] =~ s/^\s+//;
            if ( defined($2) ) {
                $lines[-1] .= $2;
                $state->{buf} = $3;
                $state->{state} = $STATES->{LOOKING_FOR_LT};
                return {
                    token => $TOKENS->{tag},
                    lines => \@lines,
                };
            }
            delete $state->{buf};
            $state->{state} = $STATES->{LOOKING_FOR_END_OF_TAG};
        }
    } # /while ( $state->{state} == $STATES->{LOOKING_FOR_LT} ) {

    while ( $state->{state} == $STATES->{LOOKING_FOR_END_OF_CDATA} ) {

        delete $state->{buf} if ( (defined $state->{buf}) && $state->{buf} eq '' );

        if ( not defined $state->{buf} ) {
            fill_buf( $state, $ref_indent_level );
            if ( not defined $state->{buf} ) { # no more data.
                $state->{state} = $STATES->{EOF};
                if ( @lines ) { # we have partial data, so return it.
                    return {
                        token => $TOKENS->{cdata},
                        lines => \@lines,
                    };
                }
                return undef;
            }
        }
        if ( $state->{buf} !~ /^(.*?)(\]\]>)(.*)$/ ) {
            push @lines, $state->{buf};
            delete $state->{buf};
        } else {
            push @lines, $1 . $2;
            $state->{buf} = $3;
            $state->{state} = $STATES->{LOOKING_FOR_LT};
            return {
                token => $TOKENS->{cdata},
                lines => \@lines,
            };
        }
    }

    while ( $state->{state} == $STATES->{LOOKING_FOR_END_OF_COMMENT} ) {

        delete $state->{buf} if ( (defined $state->{buf}) && $state->{buf} =~ /^\s*$/ );

        if ( not defined $state->{buf} ) {
            fill_buf( $state, $ref_indent_level );
            if ( not defined $state->{buf} ) { # no more data.
                $state->{state} = $STATES->{EOF};
                if ( @lines ) { # we have partial data, so return it.
                    return {
                        token => $TOKENS->{comment},
                        lines => \@lines,
                    };
                }
                return undef;
            }
        }
        if ( $state->{buf} !~ /^(.*?)(-->)(.*)$/ ) {
            push @lines, $state->{buf};
            $lines[-1] =~ s/^\s+//;
            delete $state->{buf};
        } else {
            push @lines, $1 . $2;
            $lines[-1] =~ s/^\s+//;
            $state->{buf} = $3;
            $state->{state} = $STATES->{LOOKING_FOR_LT};
            return {
                token => $TOKENS->{comment},
                lines => \@lines,
            };
        }
    }

    while ( $state->{state} == $STATES->{LOOKING_FOR_END_OF_TAG} ) {

        delete $state->{buf} if ( (defined $state->{buf}) && $state->{buf} =~ /^\s*$/ );

        if ( not defined $state->{buf} ) {
            fill_buf( $state, $ref_indent_level );
            if ( not defined $state->{buf} ) { # no more data.
                $state->{state} = $STATES->{EOF};
                if ( @lines ) { # we have partial data, so return it.
                    return {
                        token => $TOKENS->{tag},
                        lines => \@lines,
                    };
                }
                return undef;
            }
        }
        if ( $state->{buf} !~ /^([^>]*?)(>)(.*)$/ ) {
            push @lines, $state->{buf};
            $lines[-1] =~ s/^\s+//;
            delete $state->{buf};
        } else {
            push @lines, $1 . $2;
            $state->{buf} = $3;
            $lines[-1] =~ s/^\s+//;
            $state->{state} = $STATES->{LOOKING_FOR_LT};
            return {
                token => $TOKENS->{tag},
                lines => \@lines,
            };
        }
    }

    return undef if $state->{state} == $STATES->{EOF};

    die "Logic error line:" . __LINE__ . "\n";
}

sub is_a_close_tag {
    my ( $token ) = @_;
    return ( $token->{token} == $TOKENS->{tag} && $token->{lines}->[0] =~ m{^</} ) ? 1 : 0
}


sub is_an_open_tag_that_we_indent {
    my ( $token ) = @_;

    return 0 if $token->{token} != $TOKENS->{tag};
    return 0 if $token->{lines}->[0] =~ m{^<[/!?]}; # do not indent </ <? <! 
    return 0 if $token->{lines}->[0] =~ m{^<(br|p)\s*/?\s*>}i; # do not indent <br> <p>
    return 0 if $token->{lines}->[-1] =~ m{/\s*>}; # do not indent if tag closed itself />
    return 1;
}

sub print_token {
    my ( $token, $compact ) = @_;
    for my $line (@{$token->{lines}}) {
        if ( not $compact ) {
            print $token->{indent}, $line, "\n";
        } elsif ( $compact == 1 )  {
            print $token->{indent}, $line;
        } elsif ( $compact == 2 )  {
            print $line;
        } elsif ( $compact == 3 )  {
            print $line . "\n";
        }
    }
}

sub flush_output {
    my ( $output_buffer ) = @_;
    while( my $token = shift @{$output_buffer} ) {
        print_token( $token );
    }
}

# Avoid adding newlines by looking for sequences like <tag>non_tag_data</tag>
sub add_to_output {
    my ( $output_buffer, $token ) = @_;

    push @{$output_buffer}, $token;

    while( @{$output_buffer} ) {

        if ( $output_buffer->[0]->{token} != $TOKENS->{tag} ) {
            print_token( shift @{$output_buffer} );
            next;
        }
        return if @{$output_buffer} <= 1;

        if ( $output_buffer->[1]->{token} != $TOKENS->{non_tag_data} ) {
            print_token( shift @{$output_buffer} );
            next;
        }
        return if @{$output_buffer} <= 2;

        if ( $output_buffer->[2]->{token} == $TOKENS->{tag}
        && is_an_open_tag_that_we_indent( $output_buffer->[0] )
        && is_a_close_tag( $output_buffer->[2] ) ) {
            print_token( shift @{$output_buffer}, 1 );
            print_token( shift @{$output_buffer}, 2 );
            print_token( shift @{$output_buffer}, 3 );
            return;
        } else {
            print_token( shift @{$output_buffer} );
            print_token( shift @{$output_buffer} );
        }
    }
}

sub main {
    my $state = {
        state => $STATES->{LOOKING_FOR_LT},
    };
    my $indent_str   = "    ";
    my $indent_param = " ";
    my $indent_level = 0;
    my @indent = ('',);

    my ($output_buffer) = [];

    init();

    while( my $token = find_a_token( $state, \$indent_level ) ) {

        if ( is_a_close_tag( $token ) ) {
            $indent_level = 0 if --$indent_level < 0;
        }
        $token->{indent} = $indent[$indent_level];

        # input:  <foo><bar>baz</bar></foo>
        # output if (not $COMPACT):  <foo>\n<bar>\nbaz\n</bar>\n</foo>\n
        # output if (    $COMPACT):  <foo>\n<bar>baz</bar>\n</foo>
        if ( not $COMPACT ) {
            print_token( $token );
        } else {
            add_to_output( $output_buffer, $token );
        }

        if ( is_an_open_tag_that_we_indent( $token ) ) {
            if ( ++$indent_level >= @indent ) {
                push @indent, ($indent_str x $indent_level);
            }
        }
    }
    if ( $COMPACT ) {
        flush_output( $output_buffer );
    }
}

main();

r/ScriptSwap • • Mar 03 '12

[bash]unrar your .rar files into the directories with the rar and create a playlist

7 Upvotes

so I have a big directory with alot of sub directories... each of these sub directories might have just a series of rar files... or it might have a "season" of rar files... anyway, instead of unraring them into the $PWD... this unrars them into the directory where the rar is, thus keeping them organized the way I acquired them

http://sprunge.us/ZCMW

!/bin/bash

playlist="$PWD/new.txt"

excludes="$PWD/exclude.txt"

find all new rars and zips

filtered () {

find -type f ( -iname ".rar" -o -iname ".zip" ) |grep -vF -f "$excludes"

}

remove and create a new playlist for new files

[[ -f $playlist ]] && rm "$playlist" && touch "$playlist"

create an excludes file if none already exists

[[ ! -f $excludes ]] && touch "$excludes"

while read file; do

contents=${file%/*} #basically does dir name, but no execution required

I don't have any .zip files, but if you did you would have to handle that here

-o- makes it not overwrite anything so you don't have to say no if the files

has already been unrared

unrar -o- x "$file" "$contents"

   #find your recently unrared file... *cough*video... and add it to a playlist

   #to play with mplayer -playlist new.txt

find "$contents/" -type f ( -iname ".avi" -o -iname ".mkv" -o -iname "*.mp4" ) |\

     grep -vF -f $playlist|egrep -iv "sample" >> $playlist

   #Adds the rars to exclude.txt to so it doesn't attempt to extract the files again

echo $file >> $excludes

done < <(filtered) #apply the new rar filter to read file

edit: fixed formatting...


r/ScriptSwap • • Mar 03 '12

[bash] Post to Identi.ca

7 Upvotes

I wrote this script last year as a quick way to post to identi.ca when I was in a terminal. Very quick and dirty. Here is the Github for those interested: https://github.com/k4k/pub-scripts

#!/bin/bash
#
# Author: Ted W.
# Date: 2011-06-23
#
# Take the input from $2, prompt for a password and then push $2 to identi.ca.
# This is done using curl and identi.ca API. Adjust the information in the
# section labeled "USER INFO" before using this script.

# ********************
# **** USER INFO ***** 
# ********************
username="Username"
#
# *****************************************************************************
# ******* You don't need to edit anything below here if you don't want. *******
# *****************************************************************************
status=$2
post() {
    if [ "$username" = "Username" ]
        then
            echo "You need to edit $0 and add your username to the "USER INFO" section before you can use the script."
            exit 1
    fi
    # Prompt user for password and hide user input
    stty -echo
            while [ -z $pass ]
                    do
            read -p "Enter your password: " pass
            done
    stty echo

    # Pass the information to curl
    curl -u $username:$pass -d status="$status" https://identi.ca/api/statuses/update.xml
}
case "$1" in
    post|update)
            post
            ;;
    *)
            echo -e $"Usage: $0 {post|update} \"Text to post\"\n\tPost the text inside of the quotes."
           RETVAL=1
esac

r/ScriptSwap • • Mar 02 '12

(semi-automatically) rename movies

7 Upvotes

Description:

this script goes through a folder of movie files and opens the IMDB page for every movie to let you chose a new name.

I made this to add a year-tag to my file names and basically clear them up without too many interaction.

It works like this: you run the script with a folder as parameter. for each file it finds it queries you for an IMDB search-string. The reason is, file names are often pretty fucked up and IMDB won't find results, so it shows you an empty shell at first.

you can hit "up" to display the file name and then edit out the misleading parts (like Deliverance.MAXSEED-SUPERTORRENTS.1080p.avi becomes Deliverance).

hit enter and your browser will show the IMDB results. It's supposed to be used with the 2 windows side by side; terminal and browser. Now you can read the actual movie title, and year.

The next prompt shows up and asks you for the new file name. again, hitting "up" will show you previous entries; the original file name and your previously edited query string. Edit the query or original filename to get your desired new filename (like Deliverance[1972].avi) and hit enter.

file gets renamed, repeat with the next...

Example:

tim@enigma:~/movies$ python test.py .
=========================================
Old Name:  Deliverance.MAXSEED-TORRENT.avi
IMDB query--> 
(hit "up")
IMDB query--> Deliverance.MAXSEED-TORRENT.avi
(edit...)
IMDB query--> Deliverance
(enter) ... browser shows result
New Name--> 
(hit "up")
IMDB query--> Deliverance
(edit)
IMDB query--> Deliverance[1972].avi
(hit enter)
=========================================

Comments:

I'm not sure if this is useful to anyone but me, but there you go...

It's really easy to use and pretty fast as well! think about renaming a lot of files, terminal or GUI this will take some time! this script makes it easy and fast with the "intelligent" shell and can be easily adapted for anything else; doesn't have to be IMDB and movies...

I used this with another script that first moves any movie-file into a folder by the same name to have a common ground (one folder per movie, since some already come in folders; others as single files)

Script:

#!/usr/bin/python

import os, sys, shutil, readline, webbrowser

dir = sys.argv[1]

repl = []
for file in os.listdir(dir):
	path = "%s/%s" % (dir, file)

	if os.path.exists(path):
		print "========================================="
		print "Old Name: " + file
		readline.add_history(file)
		
		query = raw_input("IMDB query--> ")
		webbrowser.open("http://www.imdb.com/find?s=all&q=%s" % query)
		
		newname = raw_input("New Name--> ")
		readline.clear_history()
		repl = [(dir + "/" + file), (dir + "/" + newname)]
		shutil.move(repl[0], repl[1])