Tag Archives: Linux

Shell script: recursive find/replace

Lately I had a requirement of finding & replacing a specific string from all the files under a directory tree, while keeping the file permissions intact. Here is the shell script that I eventually came up..


cd target_dir

for _file in `find .`;
  if [ ! -d $_file ]; then
    sed "s/SEARCH_STR/REPLACE_STR/g" $_file > tmp; cp tmp $_file; rm tmp;

Hope this would help somebody.. disfrutar!

Create static and shared libraries in Unix

Static Library
Lets first look at how static library can be created and used :

(a) Compile print.c to get an object file :
gcc -c print.c -o print.o

(b) Create a static library (archive) of the object file :
ar rcs libprint.a print.o

According to *nix norms, static library’s name should start with ‘lib’ and have ‘.a’ extension. ar is a unix tool to create, modify and extract from archives.

(c) Now compile main.c and link it statically to the library.
gcc -static main.c -L. -lprint -o statically_linked

$ ./statically_linked
hello world!

Shared Library
One of the most important things to note while creating shared libraries is the object files should be compiled with -fPIC option (position-independent code).

(a) gcc -fPIC -c print.c -o print.o

(b) gcc -shared -o libprint.so print.o

(c) gcc main.c -o dynamically_linked -L. -lprint

$ LD_LIBRARY_PATH=. ./dynamically_linked
hello world!

Note: Detailed explanation of the above used gcc switches can be found in gcc manual pages.