Tag: bash

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.