Showing posts with label grep. Show all posts
Showing posts with label grep. Show all posts

Friday, April 23, 2010

LINUX: If-Else Shell Command (OR operator)

A useful command is the || operator that can be used on the linux command line. It is similar to saying "if not, then do". An example of usage would be if you wanted to put something in a script that would launch a tool, say cervisia for example, but you want to make sure that if it is already running, another instance isn't launched, you could do the following.
ps ux | grep -q cervisi[a] || cervisia . &

Now, there is an interesting thing being done with grep. In order to prevent grep from finding itself in the running processes list, use a regular expression for the last character of the process name you are looking for. Hence, the "a" in cervisia is put in brackets [] to make it a regular expression and prevent the duplication of showing the grep command in the results. Note that the two commands above, ps and grep, can be accomplished with the more efficient pgrep command, which is the combination of the two commands already part of the linux shell.

Tuesday, April 20, 2010

Search & Replace using Perl command

Searches for all files recursively that contain <string2replace> (put any string you want here, this is just for my example) and prints out a list of just the filenames.
The xargs command then passes that list to perl. Our friend perl then does -p to run script on every line of the file, -i to edit in place, -e run the following script (input from command line), 's/???/!!!/g' replaces ??? with !!! and /g says to do it for multiple occurrences on the same line. Use the first command without -i and piped to less to just see an output of all the changes it will make if using -i just to check first. The -i does an inline replace and that is permanent (shows nothing on screen). Without the -i it sends the expected results to standard out (shows it on the screen) but doesn't actually do the change. Think of it as preview-mode.

First test it to see if it looks good.
$ grep -lr <string2replace> . | xargs -n1 perl -p -e 's/<string2replace>/<replacement>/g' | less

Do it for real.

$ grep -lr <string2replace> . | xargs -n1 perl -p -i -e 's/<string2replace>/<replacement>/g'