28

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.

Aaron Perry
  • 1,021
  • 1
  • 13
  • 33

4 Answers4

57

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.

zedfoxus
  • 35,121
  • 5
  • 64
  • 63
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).

NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43
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.

Jeff Schaller
  • 2,352
  • 5
  • 23
  • 38
frawau
  • 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 08 '21 at 10:29