You are on page 1of 3

Bash, grep string in file with file name

and line number.


Not a very new pro tip, but always very useful.

This command tries to find the input string in the specified files (or all files in a folder
with *).
Here is the break-down of the parameters:

 -r stands for recursive


 -n for showing line numbers
 -w finds whole words

It shows file name, line and match in this order.

grep -rnw "tests" ./src/sicp_clojure/*

./src/sicp_clojure/1_1_exercises.clj:12:; See tests at the bottom.


./src/sicp_clojure/1_1_exercises.clj:162:(t/deftest tests
./src/sicp_clojure/1_1_samples.clj:41:(t/deftest tests

Bash/Shell script quick cheat sheet


SHELL

SCRIPT

TIPS

TESTING

SERVER

VARIABLE

CRONTAB
CHEATSHEET

LINUX

BASH

I don't create enough bash scripts to keep in mind everything. You'll find below what I
need to get back in business :

How to declare a function :


my_function() {
mkdir $1
}
How to call a function with a condition :
[ $zero -eq 0 ] && { my_function "directoryname" ; }
Get the current folder of the current script :
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
Get the dereferenced path (all directory symlinks resolved), do this:
DIR="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
Get the return code of a script :
command param
STATUS_CODE=$?
[ $STATUS_CODE -eq 0 ] && echo "Ok it has worked"
[ $STATUS_CODE -ne 0 ] && echo "Ouch, something bad happened"
Just an other way to write this (but you can do things on several lines) :
[ $STATUS_CODE -eq 0 ] && {
echo "Ok it has worked"
} || {
echo "Ouch, something bad happened"
}
Variable testing :
if [ -z $X ]; then
echo "the variable X is empty"
fi

[ -s $file_path ] && echo "the file exists and is not empty"


Careful : an empty string return true with -s, you should use -z
[ -z $X ] || echo "not empty"

[ -z $X ] && echo "empty" || echo "not empty"


Remove * except file :
rm !(file)
rm !(file1|file2)
For loop
for file in `ls`
do
echo file
done
Iterative loop
for VARIABLE in 1 2 3 4 5 .. N
do
command1
command2
commandN
done
Remove or replace a string
ok = "smting.mp3"
echo ${ok//.mp3} #return "somting"
Read a file line by line
while read line
do
command "${line}"
done < file.xt

You might also like