Printing characters before/after a certain pattern in a file in Linux

Many times it happened for me that I want to look for a certain pattern in a big text file and print the some or all characters after / before it. One that I was making my own dictionary from a huge text file that I have gathered before I found a way by searching on the internet. Now after a while I have decided to write post on it to help to the people who want to such a this thing.

Basically for searching for a certain pattern in a text file in Linux shell (terminal) many commands like Egrep and Awk are available. I believe that without example explanation about those commands are futile, therefore, lets take a look at the example.

Imagine that you want to print the rest of the line after finding “=” pattern in the file. So you can select either of below commands,

$ egrep -o '=[^@]+' YourFileName

$ cat YourFileName | awk 'match($0,"="){print substr($0,RSTART+1)}'

Now if you want to do the same thing before “=” you can use following line

$ egrep -o '^[^=]+' YourFileName

For printing numbers of characters until reaching to especial charcters like SPACE or something else you can be the following command,

$ egrep -o '=[^ ]+' YourFileName

Hint: be careful about the space between “^” and “]”. If you want to put especial character you should replace it between those two symbols.

Now just imagine you want to print certain number of characters (like three characters) after finding “=” sign in your file,

$ cat YourFileName | awk 'match($0,"="){print substr($0,RSTART+1,3)}'

You also can include “=” in printing with using below line,

$ cat YourFileName | awk 'match($0,"="){print substr($0,RSTART,3)}'

If you want to print certain number of characters (like five characters) before “=” symbol in your file then use the following command,

$ cat YourFileName | awk 'match($0,"="){print substr($0,RSTART-5,5)}'

Finally, Awk and Egrep commands are very powerful in text processing, matching especial pattern , and many more things. In this post I just demonstrated some basic functionalities of mentioned commands.

This link plus this contain useful tutorials about Awk command. I highly recommend to read and take a look at them.

More information can be found in the man pages of the commands.

send your idea and information to kasra.madadipouya@geeksweb.tk

Leave a Reply