Rek Bell

Spellbook

These are personal notes to remind myself how to do certain types of actons via the command line in the terminal. Some notes are for actions I do often, others that I've only done once, but that the process I thought was worth noting.

All of these are linux commands.

A list of some useful commands:

Batch rename prefix documents in a directory

Shell scripting is useful to add a prefix for many documents contained in one directory. To do this, navigate to the right directory in the terminal. Once there, rename all *.jpg to prefix_*.jpg in the current directory. Using *.jpg means that the script will rename all of the files with a .jpg extension, I use $filename because I want to append to the filenames that I'm already using:

for filename in *.jpg; do mv "$filename" "hitobito_${filename}"; done;

For this example, I added hitobito_ to all of the files in a directory consisting of a series of numbers(001.jpg, 002.jpg, etc). So an image once named 001.jpg was renamed to hitobito_001.jpg.

Optimizing a gif

Mogrify is a command used in ImageMagick, it is very destructive so if you want to keep the original file back it up in another folder.

-layers option. Optimizes any layers in the gif
-fuzz option. Specifies that colors within a certain tolerance can be considered the same color.

mogrify -layers 'optimize' -fuzz 7% mygif.gif

Resizing a gif

-coalesce. This option in ImageMagicks creates a complete view of the animation at each point rather than as an animation sequence. Such a sequence is much easier to study, edit, modify and re-optimize.

convert example.gif -coalesce temporary.gif

Then enter...

convert temporary.gif -resize 24x24 smaller.gif 

Another ImageMagick command, in which temporary.gif is the coalesced input file, and smaller.gif is the output file.

How to convert a gif to video

Using FFMPEG, this is a useful command when the goal is to upload gifs on Mastodon (they have to be converted to video)

ffmpeg -i animated.gif -movflags faststart -pix_fmt yuv420p -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" video.mp4

movflags. This option optimizes the structure of the MP4 file so the browser can load it as quickly as possible.
pix_fmt. MP4 videos store pixels in different formats. We include this option to specify a specific format which has maximum compatibility across all browsers.
vf. MP4 videos using H.264 need to have a dimensions that are divisible by 2. This option ensures that’s the case. [Source]

Compressing an mp4 file

-i input.mov specifies the input video file, -c:v libx264 sets the video compression codec to H.264 (libx264), -pix_fmt yuv420p changes the ProRes pixel format (4:2:2) to H.264 compatible pixel format (4:2:0).

ffmpeg -i input.mov -c:v libx264 -pix_fmt yuv420p output.mp4

Convert .mts to .mp4

ffmpeg -i input.mts -c:v copy -c:a aac -strict experimental -b:a 128k output.mp4

How to compress a PDF

To compress a PDF file, use Ghostscript. Ghostscript can modify PDF documents, it can convert PDF to images, extracting text etc.

tar -xzf ghostscript-9.55.0.tar.gz
./configure
make
sudo make install

Enter the following command to compress a PDF, in which /prepress for dPDFSETTINGS means a resolution of 300 dpi but bigger size, /ebook would mean medium quality output (150 dpi) with moderate output file size, and /screen would mean lower quality output (72 dpi) but smallest possible output file size.

gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/prepress -dNOPAUSE -dQUIET -dBATCH -sOutputFile=compressed_PDF_file.pdf input_PDF_file.pdf

Format external hard drive

Find out the path(physical mount address) for the hard drive to format the correct storage device.

df -h

Say the device is under /dev/sda1... unmount the HD:

sudo umount /dev/sda1

Enter your desired name for your formatted device instead of 'NAME'. The FAT32 file system is compatible with all mainstream operating systems, but it has transfer limit of 4GB. If you want larger files, choose exFAT(although it isn't cross-platform compatible).

sudo mkfs.vfat -n 'NAME' -I /dev/sda1
or
sudo mkfs.exfat -n 'Vincento' -I /dev/sda1

Install fonts

To install a font on your system(all accounts), create a directory with the font name(say the font name is Funkyboy):

sudo mkdir /usr/share/fonts/funkyboy

Move the font to the 'funkyboy' directory. It's possible to specify a filename, but if '*' is used all .ttf files will be moved to the new location (useful if moving several fonts).

sudo mv *.ttf /usr/share/fonts/funkyboy/

Update your system's font cache so the new fonts can be integrated.

sudo fc-cache -f -v

Confirm that the fonts were installed:

fc-list | grep "funkyboy"

If creating variations on that same font(bold, italic..), add them to the main directory of that font(Funkyboy).

Uxn commands

When using tool from a local repository, and that it needs an update. Write the following after pulling the update:

make install

In terminal to install update, re-launch tool.

Finding a file by name

To find files and directories with a certain name use the terminal, use the -name option and put the name in quotes:

find . -name "picard.jpg"

Markdown to HTML with pandoc

pandoc doc_name.md -o doc_name.html

Copying hexadecimal code from Nasu

Select the sprite in Nasu, then ctrl+c. Open a terminal window, and navigate to the folder where the file is located. Type:

hx .snarf

Copy the text from the terminal ctrl+option+c and paste it where you want

Changing the computer's time/timezone

To change the timezone, first find the timezone in the list using the following command(to cycle through the list, enter line numbers and press enter):

timedatectl list-timezones

Then, set the chosen timezone using:

timedatectl set-timezone "timezone"

Ex: timedatectl set-timezone "America/Vancouver"

To change the time:

timedatectl set-time "yyyy-MM-dd hh:mm:ss"

Download webpage with wget

To download a website for local viewing:

wget --page-requisites --convert-links --span-hosts --no-directories https://www.example.com

Sourced from Tyler Smith.

Change repo from master to main

Master is an antiquated and innapropriate term. To change the repository branch to main, navigate to the correct repository, then enter:

git branch -m master main

git push -u origin main

git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/main

# change default branch

git push origin --delete master

Using Cmus

Control

Search

Playlist editing

To add new music, press 5, then navigate to music using a. Switch back to simple view by pressing 2, or to tree view with 1.

Modifying song's metadata

To modify the metadata of a song, you can use VLC by opening a song with it, then going to Tools>Media Information (be sure to save).

It's also possible to do in the terminal, by installing eyeD3:

sudo pacman -S python-eyed3

Then run:

eyeD3 -a 'Artist name' -A 'Album name' -t 'Song name' song.mp3

Artist (-a/--artist), album (-A/--album), title (-t/--title), and track number (-n/--track-num).

List sourced from Rostiger's website.

How to kill an unresponsive program

pstree -p

Identify parent process.

kill 1234

Where 1234 is the process ID I found using pstree. If application has not been terminated, do this:

kill -9 1234

Ripping audio/video YouTube

NOTE. Youtube-dl doesn't work anymore, it is now necessary to use yt-dlp, to install:

sudo pacman -Syu yt-dlp

Refer to the installation guide for other linux distributions or OSs. The new command for ripping audio:

yt-dlp -f 'ba' -x --audio-format mp3 https://www.youtube.com/watch?v=dQw4w9WgXcQ  -o '%(id)s.%(ext)s'

A simpler option is:

yt-dlp -x -f bestaudio https://youtube.com/insertaddress

To download videos...

yt-dlp https://www.youtube.com/watch?v=f6wtF_2eyrU

If you want to select a specific format, or audio only, enter the following along with the youtube video url:

yt-dlp --list-formats https://www.youtube.com/watch?v=f6wtF_2eyrU

You'll get a list of formats in the command line window. Each option is labelled with a number (far left). Options include versions of the video without audio in a variety of formats (mp4, webm), others are for audio only. If the goal is to get audio only, then one would write -f 140 in the command line:

yt-dlp -f 140 https://www.youtube.com/watch?v=f6wtF_2eyrU

To specify a name for the video, append -o '%(id)s.%(ext)s', like so:

yt-dlp https://www.youtube.com/watch?v=f6wtF_2eyrU -o '%(id)s.%(ext)s'

pandoc commands

To export a text file formatted in html to markdown (as a .txt file).

    pandoc -o filename.txt filename.html

To export mardown text file into a styled pdf (see how to install pandoc, as well as TexLives and other useful extensions).

pandoc filename.txt --pdf-engine=xelatex -o filename_export.pdf

Sublime shortcuts

To select the space before the first character on every line in a paragraph.

shift+right, then crtl+d (repeat d key to select additional lines).

Checking battery health

To check battery health on your laptop time the following command:

upower -e

You'll see the following:

/org/freedesktop/UPower/devices/line_power_ADP1
/org/freedesktop/UPower/devices/battery_BAT0
/org/freedesktop/UPower/devices/DisplayDevice

Enter:

upower -i /org/freedesktop/UPower/devices/battery_BAT0

Check energy-full and energy-full-design to see the performance of your battery. To know if the battery needs to be replaced, divide the number next to “Energy when full” by “Energy (design)”, and multiply the result by 100. You’ll get a percentage.

The percentage you get is how much your battery holds of its original capacity. If the number is >50%, it might be time to replace the battery.

Creating a working .desktop file

Open a text editor. Paste and edit the following:

[Desktop Entry]
Version=x.y
Name=ProgramName
Comment=This is my comment
Exec=/home/alex/Documents/exec.sh
Icon=/home/alex/Pictures/icon.png
Terminal=false
Type=Application
Categories=Utility;Application;

Version is the version of the file.
Name is the application name, for example "krita" or "thunderbird".
Comment is a short description of said application.
Exec is the path to the executable application. Icon is the path to the icon you wish to use for the application.
Terminal is whether you want the application to run in a terminal window or not.
Type specifies the type of launcher file (other examples include link, or directory).
Categories is used to categorize applications.

Save the .desktop file. While in the same folder, open the terminal window and type the following to move the .desktop file to /usr/share/applications, or write the path to the .desktop file:

sudo mv programname.desktop /usr/share/applications

Navigate to usr/share/applications, find the file you just moved, select and drag it onto the launcher panel. Now your launcher (.desktop file) is locked on your launcher dash.

Update remote from http(s) to ssh

Look inside .git/config in your repo, and change the relevant remotes to look like:

url = git@github.com:/.git

Export images to PDF with ImageMagick

Exporting images to PDF using Gimp has its limits, it doesn't work with big images for PDFs, so Imagemagick is a good alternative. The following command takes all of the images in a folder and makes a PDF out of them.

convert *.jpg documentname.pdf

Export images to PDF with GIMP

Combine images in same file on layers. Export as a .mng file using the default export settings. Convert to PDF using imagemagick. If you don't have it, install it first.

sudo apt-get install imagemagick

Convert your files, that's it.

convert -reverse document.mng document.pdf

Back to top.

Make appimage executable

chmod +u 

Back to top.

How to format USB on Linux

Insert the USB flash drive or SD card into your Linux machine and find the device name using the lsblk -fp command:

$ lsblk -fp
NAME                            FSTYPE      LABEL       UUID     MOUNTPOINT
/dev/sda
└─/dev/sda1                     LVM2_member             c52... 
  ├─/dev/mapper/mint--vg-root   ext4                    183...   /
  └─/dev/mapper/mint--vg-swap_1 swap                    337...   [SWAP]
/dev/sdb
└─/dev/sdb1                     vfat        USB Drive   345...   /media/user/usb0

In the example above, the USB drive is recognized by the operating system as a disk named /dev/sdb with a single partition /dev/sdb1 mounted on /media/user/usb0. Unmount the USB drive if it is mounted:

sudo umount /media/user/usb0

Formatting types:

To convert to FAT32, enter desired label name (optional):

$ sudo mkfs.fat -F 32 /dev/sdb1 -n "USB Drive"

Install a terminal dictionary

Half of the online searches I make are for word definitions, or synonyms. A good physical dictionary is useful, but there are times when searching online is quicker. I didn't want to use anything with an interface, as they tend to be messy, and in this case, my needs are very simple. A terminal dictionary as for me, the better option. Enter SDCV.

SDCV, or StarDict Console Version, is the terminal utility version of StarDict extensible GUI dictionary application. Here's how to install it:

sudo apt-get install sdcv

On Manjaro...
sudo pacman -S sdcv

SDCV is now installed, but has no dictionaries to search from yet. SDCV requires files in a DICT format. You can pick the ones you want from the list here, recommended by StarDict. To start, you can download the Collaborative International Dictionary of English.

Next, navigate to the folder where you will place your dictionary.

cd /usr/share

Make a directory named stardict, and another in it named dic. To make a directory, use sudo mkdir followed by the name of your new directory.

Next, we'll uncompress and move the dictionary in one go, using the following command. Modify INSERTNAME with the name of the file you've downloaded.

sudo tar -xjvf INSERTNAME -C /usr/share/stardict/dic

Enter your password, and voila! To use SDCV, type sdcv followed by the word you're looking for, for example:

sdcv tortilla

Spritesheet conversion to GIF

ImageMagick can convert spritesheets to gif animations, here is the recipe I used:

convert -dispose 3 -delay 20 -loop 0 input.png -crop 64x64 +repage output.gif

Here is a breakdown of the recipe:

-dispose 3 'dispose" defines the way the displayed image is modified after the current frame of an animation has gone past, and before another frame is overlaid.
3 refers to 'previous', which clears to the image prior to the current frame's overlay.
-delay 20 displays the next image after pausing for a number of seconds.
-loop 0 set to zero the animation repeats an infinite number of times.
input.png is my starting spritesheet.
-crop cuts out one or more rectangular regions of my image to 64x64 pixels. For my animation, I had 5 frames, 64 is the width/height of the bounding box of the sprite (full width 320px / 5).
+repage adjusts the canvas and offset information of the image.
output.gif is the resulting, assembled gif image.

Back to top.