Geronimo89.dk

A blog about me, my doings and everything I think deserves attention.

bash: grep

Grep ist eines dieser kleinen Programme, die unendlich viel Zeit sparen können. Zum Beispiel wenn man gerade in der Ellenlangen Ausgabe eines anderen Programms nach etwas Bestimmten sucht. Zum Beispiel nach der Bezeichnung seiner liebsten Razer Maus:

geronimo@Zero-1:~$ lsusb | grep Razer
Bus 002 Device 002: ID 1532:0002 Razer USA, Ltd

Weitaus praktischer wird der Befehl noch, wenn man ein älteres Webprojekt nach einer bestimmten Variable für das Passwort durchsuchen muss. Da der Code nicht dokumentiert und die Dateien nicht eindeutig benannt war, musste ich gleich mehrere Dateien danach durchsuchen. Hier ein weiteres Beispiel:

geronimo@Zero-1:$ grep upload -rH *.php*
upload2.php:<title>valid upload script</title>
upload2.php:<h2>select the file you want to upload:</h2>
upload2.php:  <form enctype=”multipart/form-data” action=”upload.php” method=”POST”>

Wie wir sehen zeigt der Befehl die Ausgabe und führt dank des -H Parameters auch den Dateinamen an. Wer nicht lange suchen, sondern finden will, sollte sich also schleunigst mit grep vertraut machen icon wink bash: grep
Give me the first comment

Batch editing html or text files

At work, I’ve been more than once exposed to older web sites that had to be changed. Problematic about this was, that I would have to edit about 30 html files to change an email address or change a part of the menu that was stored on every single html page. As I thought, that this was far too annoaying, I decided to write a script for it.

The stream editor (sed) that is pretty much standard on basically every distribution and a core element offers the search and replace function, but I will stop to annoy you and just give you the script:

#!/bin/bash
# a little help by Jonathan M. Hethey
# use:
# 1. put in directory with files to edit
# 2. change variables replace and with
# declare the variable you want to have replaced
replace="old_pic.png"
# and the string you want to replace it with
with="new_pic.png"
# the script will do it on all files with a certain file suffix, .html in this case
for filename in *.html
# loop it for all files found with .html
do
# search and replace it
sed -i "s/$replace/$with/g" $filename
# echo all files processed, this gives you information which files were worked on (probably all .html files, because sed will read all, but only work on the ones where there is something to be replaced.
echo $filename
# end the loop
done;

A little struggle was to get the variables (I only added for you, my readers) to work. It’s all about using ” instead of ‘ because bash does not interpret variables inside ‘.
Download: replacer.sh

Give me the first comment