Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract The Second Word In A Line From A Text File

Tags:

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.

like image 688
Aaron Perry Avatar asked Aug 25 '14 18:08

Aaron Perry


2 Answers

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.

like image 77
zedfoxus Avatar answered Sep 25 '22 08:09

zedfoxus


In case of sed is needed /only available

sed '^ *[^ ]* *\([^ ]*\) .*/\1/' YourFile

Take second non blank group (assuming there is at least 1 blank after the word

But I prefer cut for speed (and awk if any manip is needed).

In fact it mainly depend on next action in script (if any).

like image 43
NeronLeVelu Avatar answered Sep 26 '22 08:09

NeronLeVelu