27

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.

1
  • Which do you need - word or character?
    – Ed Morton
    Aug 25, 2014 at 20:16

4 Answers 4

56

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.

2

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).

2

you can use a shell builtin command:

#!/bin/sh
set -f && set +f -- *   CRISTOBAL  AL042014  08/05/14  12  UTC   *
echo $2

or better readable using an alias:

#!/bin/sh
alias explode='set -f;set +f --'

LINE='*   CRISTOBAL  AL042014  08/05/14  12  UTC   *'
explode $LINE
echo $2

The "-f" means:
Disable file name generation (globbing),
so an asterisk will not expand to a filename.
Switching it off and on in one shot sets the default again. This works in all POSIX shells.

-1

I know it is old but, @NeronLeVelu was hair short of what I needed in a pipe.

ip link show wlan0 | grep 'link'| sed 's/^ *[^ ]* *\([^ ]*\) .*/\1/'

Was what I used to extract the MAC address. I could not use awk for other reasons.

1
  • 1
    I'm glad you could achieve what you wanted, but this doesn't answer OP's question in any way. Consider leaving a comment under @NeronLeVelu's answer instead
    – Tranbi
    Aug 8, 2021 at 10:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.