Code Snippets

Testing this out to see if I can just use a blog post (or page) to store these myself. Accessible from anywhere, public (because, why not?), easy to copy/reuse. Perfect.

Rename files in all subdirectories

sudo rename /s/old-file.txt//new-file.txt/' **/*

Delete line X only if blank in all files in a folder

find ./ -type f -exec sed '1{/^$/d}' {} \;

Delete a line if it matches a pattern in all files in a folder

sudo find ./ -type f -exec sed -i '/pattern-to-match/d' {} \;

Delete lines after a pattern match in all files in a folder

find ./ -type f -exec sed -e '/pattern/{n;N;N;N;N;d}' {} \;

Add line of text to the beginning of all files in a folder

find ./ -type f -exec sed -i '1s/^/<added text> \n/' {} \;

Make a folder for each file, then move files to their matching folder

If you need to rename the file, add that at the end of the mv command line

#!/bin/bash

dir="/somedir/"
for i in "$dir"*; do
  if [ -f "$i" ]; then
    filename="${i%%.*}"
    if [ ! -d "$filename" ]; then
      sudo mkdir "$filename"
    fi

    sudo mv "$i" "$filename"
  fi

done

Match line and do a search/replace for multiple characters on all files

sudo sed -i '/match:/s/to-replace/replace-with/g' *

Use find and sed to search/replace in all files in all subdirectories

find ./ -type f -exec sed -i -e 's/find-this/replace-with-this/g' {} \;

About

Retired I.T. - expat life in Mexico - aspirational writer, hacker, activist, musician, genealogist

Tags