Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 11-20 of 40 total

find line in text file, add to another text file

// Batch - search .txt / .csv / etc using argument, return matches to .txt / .csv / etc file
// skips the ---------- foo.csv returned by find alone
   1  
   2  find /i "%1" foo.csv | find /i "%1" >> bar.txt

Recursively find files by filename pattern.

Scans a directory, and all subdirectories for files, matching a regular expression. Each match is sent to the callback provided as third argument. A simple example:

   1  
   2  function my_handler($filename) {
   3    echo $filename . "\n";
   4  }
   5  find_files('c:/', '/php$/', 'my_handler');


And the actual snippet

   1  
   2  function find_files($path, $pattern, $callback) {
   3    $path = rtrim(str_replace("\\", "/", $path), '/') . '/';
   4    $matches = Array();
   5    $entries = Array();
   6    $dir = dir($path);
   7    while (false !== ($entry = $dir->read())) {
   8      $entries[] = $entry;
   9    }
  10    $dir->close();
  11    foreach ($entries as $entry) {
  12      $fullname = $path . $entry;
  13      if ($entry != '.' && $entry != '..' && is_dir($fullname)) {
  14        find_files($fullname, $pattern, $callback);
  15      } else if (is_file($fullname) && preg_match($pattern, $entry)) {
  16        call_user_func($callback, $fullname);
  17      }
  18    }
  19  }

Remove all files in a directory except *.ogg

Remove all files in a directory except *.ogg

   1  
   2  #!/bin/bash
   3  
   4  find . ! -name "*.ogg" -exec rm -f {} \; 

Active Record: Select specific column data

ActiveRecord works at the row (aka record) level, not the column level. That's not to say that you can't just get a single column of data back from the database, you can, but you won't have all the attributes if you do this so just keep that in mind. you'll probably want to map them to an array..
   1  
   2  class User < ActiveRecord::Base
   3    def self.names
   4      # find all records, then map name attributes to an array
   5      find(:all, :select => "name").map(&:name)
   6    end
   7  end
   8  
   9  # btw..
  10  .map(&:name)
  11  
  12  # is shorthand for
  13  .map { |x| x.name }

Array Search Prototype

This prototype extends the Array object to allow for searches
within the Array. It will return false if nothing is found. If
item(s) are found you'll get an array of indexes back which matched
your search request. It accepts strings, numbers, and regular expressions as search
criteria. 35 is different than '35' and vice-versa.
   1  
   2  // Examples
   3  var test=[1,58,'blue','baby','boy','cat',35,'35',18,18,104]
   4  result1=test.find(35);    //returns 6
   5  result2=test.find(/^b/i); //returns 2,3,4
   6  result3=test.find('35');  //returns 7
   7  result4=test.find(18);    // returns 8,9
   8  result5=test.find('zebra'); //returns false


   1  
   2  Array.prototype.find = function(searchStr) {
   3    var returnArray = false;
   4    for (i=0; i<this.length; i++) {
   5      if (typeof(searchStr) == 'function') {
   6        if (searchStr.test(this[i])) {
   7          if (!returnArray) { returnArray = [] }
   8          returnArray.push(i);
   9        }
  10      } else {
  11        if (this[i]===searchStr) {
  12          if (!returnArray) { returnArray = [] }
  13          returnArray.push(i);
  14        }
  15      }
  16    }
  17    return returnArray;
  18  }

Find and replace

This will search all files recursively for SEARCH_STRING and replace all occurrences of SEARCH_STRING with REPLACE_STRING throughout each unique file found. It also creates a backup of each modified file so that FILE is backed-up as FILE~ (with a tilde).

   1  
   2  grep -R --files-with-matches 'SEARCH_STRING' . | sort | uniq | xargs perl -pi~ -e 's/SEARCH_STRING/REPLACE_STRING/'

remove empty lines in VIM

// removes empty lines

   1  
   2  :%s/^[\ \t]*\n//g 

find

* This command finds all the files and removes them. The slash is to escape the semicolon. We don't want the semicolon to be taken as a command seperator. (it's a command delimitor for the parameter -exec).
find -name "*" -exec rm {} \;

* This command finds and removes all files and executes ls.
find -name "*" -exec rm {} \;; ls

* Find only regular files (not directories, sockets, etc).
find -type f -print

* Find patterns 'foo' in all files starting from the current directory(.).
find . -type f -exec grep foo {} \;

* List full pathnames of files in directory dirname.
find dirname

* Finds the file test.txt.
find . | grep test.txt

various du applications

list of folders accompanied by size (human-readable), sorted by name:
   1  
   2  du -hd 1 | sort -k 2

list of folders accompanied by size (human-readable), sorted by size:
   1  
   2  du -hd 1 | grep [0-9]K | sort -n -k 1 ; du -hd 1 | grep [0-9]M | sort -n -k 1

recursive list of folders and files, which are less, than 1MB
   1  
   2  du -ah | grep '[0-9]K' | sort -n -k 1 | less

recursive list of folders and files, which are more, than 1MB, but less, than 1GB
   1  
   2  du -ah | grep '[0-9]M' | sort -n -k 1 | less

same, but folders only
   1  
   2  du -h | grep '[0-9]M' | sort -n -k 1 | less

same, but files only
   1  
   2  find . -type f -size +2048 -exec du -hs {} \; | sort -n -k 1 | less

Find all backup files in a directory

Find out where the backup files are. Backup files end with ~, for example test.php~

   1  
   2  find . -name *~ -print


For finding and deleting them:
   1  
   2  find . -name "*~" -exec rm {} \;


The \ is for preventing the "find: missing argument to `-exec'" error
« Newer Snippets
Older Snippets »
Showing 11-20 of 40 total