Tag: bash

bash : Put the source of a webpage in a variable

When you do some bash scripting , this is often useful to get data from  webserver because they are a very simple way to exchange data from computer from computer.
to put the data that’s available on a webserver into a $var you just have to use the command :

this will fetch the data from http://server.com/file.htm in a non verbose way and put it in variable named var .

you can now do whatever you want with that $var , like greping it for example.

 

Extract values separated by character ( : , . – )

In a bash script if you find yourself with values presented that way

you might want to keep only the second or third of this values that are separated by the : character

like always , in bash there is a lot of ways to accomplish that , but i like to use a one that use the AWK utility because it’s very easy to read and understand.

my list of value is contained in a var name $var let’s extract the third value which is 18.5

Will return the value 18.5

but i can do some math operation in the utility, like :

this will return 326.5 the result of 345 – 18.5

awk is a fast and powerful text editor , there is a lot things you can do with it.

Using sed to delete a word from a string

For example in a bash script you need to delete one or more word from the string , you can use sed to do just that

sed is searching for “word to delete” and replacing it with nothing ,

you can of course pipe to that command ,

example :

the var $visitor contain the string : ‘current number of users: 234’

But only the number (234) is usefull to you ,

your can do :

the result is going to be : 234

 

Grep a line before or after a match in bash

Sometime when you grep a file on Linux you need to not only display the line where the result is found but also several lines before or after the match.

Grep as a useful function permitting you to do just that.

Let’s take an example file.

file.txt:

Title : login issue
Ticket number : 16417
Details : user password is no longer working.

Title : Broken keyboard
Ticket number : 16418
Details : the space key on the user keyboard no longer work

 

If the file is list of hundreds of this informations and you need to see only the information related to ticket 16417 you need to

cat file.txt|grep 16417

Will only return the result Ticket number : 16417  living out the useful informations

If you need to display a line after the grep match

cat file.txt| grep -A1 16417

will return :

Ticket number : 16417
Details : user password is no longer working.

But there is also useful information before  the match

You can associate the 2 options to display the line after and before

cat file.txt| grep -A1 -B1 16417

this will return all the information i need :

Title : login issue
Ticket number : 16417
Details : user password is no longer working.