Execute a command for each file in a directory recursively on Linux

I recently wanted to make a change — actually a string replacement — in every file in the current directory and all directories beneath it, perhaps filtering by file extension. In this case, I wanted to change four spaces to a tab character in every .php source file. I created a small BASH shell script file to do this, though you could also just run the command directly at the command line:

find . -type f -name '*.php' -exec sed -i 's/    /\t/g' {} \;

Explanation:

  • find lists all files, one per line, in the current directory and all subdirectories recursively
  • . (period) means current directory
  • -type f only list files, not directories.
  • -name ‘*.php’ only if the name matches * (wildcard) with “.php” at the end
  • -exec execute the following command for each result that matched
  • sed -i ‘s/    /\t/g’ replace, or substitute, one string for another. I’m searching for four consecutive spaces and replacing with t, meaning tab character. the /g at the end means global, replace each instance wherever it may appear in the file on each line. -i means “edit file in place” so the modified file is saved back to itself.
  • {} this inputs the file for the sed command
  • \; I think this finishes the -exec parameter for find. Don’t forget the backslash

To change spaces to tabs or tabs to spaces, you can also look into the expand and unexpand commands.

Overall I highly recommend learning the sed command for quick and easy find & replace operations in text files.

More examples of the find command with -exec:

Delete all directories matching a name, such as CVS, under the current directory:

cd /path/to/myproject/directory/src
find . -type d -name 'CVS' -exec rm -rf {} \;

Linux – Disk Usage (du) Sorted by Size

Here’s a simple way to find how much disk space is taken up by each folder in a directory, and sort it by size. This works in pretty much any Linux distribution (Ubuntu, Fedora, CentOS, and more).

du --block-size=MiB --max-depth=1 | sort -n
  • du is the disk usage and will, by default, recursively traverse every directory of the current one, listing the size of the directory by bytes. Without options, it isn’t very helpful (press Ctrl C to stop the process safely)
  • –block-size=MiB will convert the bytes amount to megabytes (or Mebibytes), so instead of showing 9437184 (bytes) it will show 9 MiB
  • –max-depth=1 will only list size of directories in the current directory. 2 will traverse an additional level down, and so on.
  • | sort -n will transfer, or “pipe”,  the output of the du program to the sort utility which simple sorts lines sent to it. -n tells it to sort numerically.
  • If you want to sort in reverse order, simply change n to rn
Example output:
statik@Phenom:~/Pictures$ du --block-size=MiB --max-depth=1 | sort -n
1MiB ./icons
1MiB ./USTM
1MiB ./vector
1MiB ./Webcam
3MiB ./animated
3MiB ./wallpaper
8MiB ./UltraMiami
688MiB ./2010
1600MiB ./2011
2306MiB .

As you can see, when I run this command in my Pictures folder, I have 688 MB of pictures in 2010 and 1600 MB of pictures in 2011.

You can add a shortcut to the command (an “alias”) by adding this to your ~/.bashrc or ~/.bash_aliases file

alias duinfo='du --block-size=MiB --max-depth=1 | sort -n'

The next time you open a terminal you can simply type “duinfo” and it will execute the alias. Tab completion also works.

Additional Tip: the ls (directory listing) command also supports the –block-size=MiB statement. Use –block-size=KiB for kilobytes, GiB for gigabytes, and so on.

Related Article: http://www.earthinfo.org/linux-disk-usage-sorted-by-size-and-human-readable/

Ubuntu: Configure a Keystroke to Take a Screenshot

The Mac OS has a nice screenshot interface. You press Cmd Shift 3 to take a screenshot of the entire screen and save it to the desktop. Pressing Cmd Shift 4 will display a crosshair to take a screenshot of any rectangle area of your choosing. This saves the step of cropping the image which you are most likely going to do.

You can replicate this exact functionality in Ubuntu Linux without installing anything else.

  1. Go to System -> Preferences -> Keyboard Shortcuts
  2. In the desktop section, find Take a screenshot and highlight it
  3. Press Ctrl Shift 3 (or whichever combination you would like)

There is no entry for “Take a screenshot of an area”, so we must create it.

  1. Click the Add button
  2. Name: Take a screenshot of an area
  3. Command: gnome-screenshot -a
  4. Click the newly created entry
  5. Press Ctrl Shift 4 (or whichever combination you would like)
  6. Close the window

Thats it! Now you can press Ctrl Shift 4 and take a screen shot of an area.

Using XBindKeys on Ubuntu Linux to Remap Key Commands

Once again I have started to use Ubuntu GNU/Linux to try to get away from Windows and explore more freedom respecting software. Of course there are going to be a lot of utilities you use in Windows that are not available in Linux so you have to find the equivalents. One of my must have utilities on Windows is AutoHotKey, especially since I use a TypeMatrix compact keyboard with a Dvorak layout. For example, my Z key is on the right side of the keyboard so I like to remap Ctrl + ; (semicolon) to activate Ctrl + z to undo things with my left hand.

The idea is that you use xbindkeys to listen for keyboard commands (input) and then you use xvkbd to type your desired keys (output).

Here is how to remap a combination of keys to another combination of keys on linux:

Install xbindkeys

sudo apt-get install xbindkeys

Create the default config file for xbindkeys

xbindkeys --defaults > /home/your-user-name/.xbindkeysrc

When thats done, install xbindkeys-config, the GUI for xbindkeys (note: the GUI is optional, you could just edit the config file with a text editor).

sudo apt-get install xbindkeys-config

Now the utility the actually does the “typing”

sudo apt-get install xvkbd

Once each is installed, start xbindkeys by bringing up “Run Application” with ALT -F2.

xbindkeys

If you want to launch the GUI editor you can run xbindkeys-config, but I found it to be more confusing than the text file.

Configuring your Shortcuts and Macros

Open your configuration file in your favorite text editor. It is called .xbindkeysrc in your home directory.  Use the # character to comment out lines, such as the default macros placed by the program’s author — after I installed it, Ctrl + F was launching an xterm window all the time.

At the end of the file, put this:

"xvkbd -xsendevent -text "Cz""
   control + semicolon
The second line is the keystroke to invoke the operation — kind of counterintuitive but that is how it is. Here it is listening for Control + semicolon.  To find the syntax for the key being pressed, you can run the xbindkeys-config utility and click the Get Key button. Press any key combination and it will print out what you did. From there you can just copy or edit the text of the command.
The first line is the command line operation to send when your desired key combination occurs. Here I’m running xvkbd with some flags. -xsendevent tells it to send an XEvent to whatever the active window is (and active input field). -text means type the block of text in quotes. C (backslash C) means hold Ctrl while pressing the next key, which is the letter “z”.   For more xvkbd syntax, look at http://man-wiki.net/index.php/1x:xvkbd or this chart:
- r – Return
- t – Tab
- b – Backspace
- e – Escape
- d – Delete
- S – Shift (modify the next character)
- C – Control (modify the next character)
- A – Alt (modify the next character)
- M – Meta (modify the next character)
- [keysym] – the keysym keysym
Please note that modify with “S will be ignored in many cases. For example, “aCbScDCE will be
interpreted as a, Control-b, c, Shift-D, and Control-Shift-E.
Instead of using xvkbd to send text strings, you could probably use the xmacro utility to create more advanced macros to playback. You can also run any program you want, just put the command within the double quotes.
Example: Launch Firefox with Ctrl + f
"firefox"
   control + f

Now I just have to find an easy way to reload my xbindkeysrc config file when I make changes. Right now I’m killing the process and launching it again.

Final note: you can set xbindkeys to launch on startup — in ubuntu, just go to System -> Preferences -> Startup Applications and add a new command xbindkeys.