Marius van Witzenburg We fight for our survival, we fight!

10jul/110

How to read a file line by line with Bash

Posted by mariusvw

Sometimes you want to do actions per line instead of the complete file at once.

Here is an example that you can use to read the file line by line.

#!/bin/bash
run_cmd_file() {
    while read line
    do
        chr=${line:0:1}
        case $chr in 
            "#" )  # ignore commented lines
                ;;      
            *   )   
                echo line[$line]"
                ;;      
        esac    
    done < $2
}
 
run_cmd_file filename
Geëtiketeerd als: , , , , , Geen reacties
25aug/100

How to fix inconsistent line ending (EOL) style with find and Perl

Posted by mariusvw

If you work with subversion you might get this error when you got files that have been edited on different operating systems like Windows, Linux, FreeBSD or Mac OS X.

Well, the fix is quite simple. You simply replace the wrong line endings with right ones depending of which you want. In my situation I want unix style line endings.

Replace in PHP/JavaScript files:

find ./ -name '*.php' -type f -exec perl -i -wpe 's/rn/n/g' '{}' ;
find ./ -name '*.php' -type f -exec perl -i -wpe 's/r/n/g' '{}' ;
find ./ -name '*.js' -type f -exec perl -i -wpe 's/rn/n/g' '{}' ;
find ./ -name '*.js' -type f -exec perl -i -wpe 's/r/n/g' '{}' ;

In case you want to replace them in multiple file types you can adjust the command. In this example we want to replace in the following file types:

  1. asp
  2. cfm
  3. css
  4. html
  5. js
  6. php
  7. pl
  8. txt

Use the following commands:

find ./ -name '*.asp' -or -name '*.cfm' -or -name '*.css' -or -name '*.html' -or -name '*.js' -or -name '*.php' -or -name '*.pl' -or -name '*.txt' -type f -exec perl -i -wpe 's/rn/n/g' '{}' ;
find ./ -name '*.asp' -or -name '*.cfm' -or -name '*.css' -or -name '*.html' -or -name '*.js' -or -name '*.php' -or -name '*.pl' -or -name '*.txt' -type f -exec perl -i -wpe 's/r/n/g' '{}' ;

Keep in mind, you may use these commands on your own risk. I'm not responsible if you lose your work ;-)

Now you should be able to commit your files again :-)