Linux – Use Word Delimiter

Linux – Use Word Delimiter

We have been using cut command in Linux where the delimiter is a character instead of a word or a bunch of characters.

There are number of occasions where we use cut to separate a data or format an output. Ideally I use cut with a delimiter when I need an output for some column.

A SQL output separated with pipe character (|) is simple to handle through cut.

So let’s take a quick example of a SQL output:

 Emp ID | First Name | Last Name | Department

   1    | Keith      | Baker     | Sales
   2    | Gagan      | Brahmi    | IT
   3    | Viv        | McDonald  | Finance

In the above output, if I want to fetch the First Name of all the employees I will use cut with the delimiter (-d) as the pipe character (|) and the field (-f) will be 2.

The syntax will be:

cut -d”|” -f 2 FILE

In our case, the results will be something like below:

[email protected]:~$ cut -d"|" -f 2 employees.txt
 First Name

 Keith
 Gagan
 Viv

However, cut has it’s own limitation. Using cut with the -d flag will only allow a single character to be used as a seperator/delimiter.

Linux – Use Word Delimiter

Now imagine the output similar to the one above, but instead of a single character you have a word which needs to be used as separator/delimiter.

The better alternative in such case is awk.

Linux – Use Word Delimiter using awk

So continuing the above output as an example, I have made a few changes.

The following is how the output for the file is now:

 Emp ID == First Name == Last Name == Department

   1    == Keith      == Baker     == Sales
   2    == Gagan      == Brahmi    == IT
   3    == Viv        == McDonald  == Finance

We will try to get the same output from this content using awk. We will get the First Name from this data.

The syntax will be:

awk -F”STRING” ‘{print $COLUMN}’ FILE.NAME

Where, -F stands for the value which is to be set as a field separator or delimiter.

The following is the command in our case:

[email protected]:~$ awk -F"==" '{print $2}' employees.txt
 First Name 

 Keith      
 Gagan      
 Viv

Please note that in the above example the string “==” is just an example to give you an idea of how the command can be used to your advantage.

Linux – Use Word Delimiter

No Comments

Post a Comment

Time limit is exhausted. Please reload CAPTCHA.