Extract The Second Word In A Line From A Text File

Aaron Perry picture Aaron Perry · Aug 25, 2014 · Viewed 40.8k times · Source

I am currently in need to extract the second word (CRISTOBAL) in a line in a text file.

                 *   CRISTOBAL  AL042014  08/05/14  12  UTC   *

The second word in the line "CRISTOBAL" will vary from day to day so, I just need to find a way to extract JUST the second word/character from the line.

Answer

zedfoxus picture zedfoxus · Aug 25, 2014

2nd word

echo '*   CRISTOBAL  AL042014  08/05/14  12  UTC   *' | awk  '{print $2}'

will give you CRISTOBAL

echo 'testing only' | awk  '{print $2}'

will give you only

You may have to modify this if the structure of the line changes.

2nd word from lines in a text file

If your text file contains the following two sentences

this is a test
*   CRISTOBAL  AL042014  08/05/14  12  UTC   *

running awk '{print $2}' filename.txt will return

is
CRISTOBAL

2nd character

echo 'testing only' | cut -c 2

This will give you e, which is the 2nd character, and you may have to modify this so suit your needs also.