1

Suppose I have a line of text as follows:

I have a nice car

Is there any way to get different words of the line at different positions individually (say, I want to get 'have' and 'nice' parts) without saving the line to any file. I mean, I want to apply such a method which will directly give me words at desired positions of the given line. Is there any way?

  • 8
    There are many ways. I advise you to get familiar with awk, grep, sed, cut and so on... And search the site (the text-processing tag is a good place to start). – don_crissti Sep 14 '15 at 20:38
5

bash has arrays:

line="I have * nice car"
set -f                      # disable pathname expansion
words=($line)               # no quotes around $line
set +f                      # re-enable pathname expansion

words is an index array, zero-based, so

# print the 2nd word
echo "${words[1]}"               # ==> have

# print the 2nd-last word
echo "${words[-2]}"              # ==> nice

Converting the string to an array splits the string at any sequence of characters contained in the shell's $IFS variable (default: space, tab, newline)

  • 1
    If you're going to use the split+glob operator, you should disable the glob part which you don't want here. – Stéphane Chazelas Sep 15 '15 at 6:23
  • 1
    On shells without arrays, you can do set -f; unset IFS; set -- $line and have the words in $1, $2... – Stéphane Chazelas Sep 15 '15 at 16:07
4

Use awk try this:

$ awk '{print $2, $4}' file

Where $x is the word position, this is delimited by whitespaces

e.g.

$ echo "I have a nice car" | awk '{print $2, $4}'
have nice
3
line="I have a nice car"
fields=$(echo "$line" | awk '{ print $2 " " $4 }')

That splits by whitespace. If you want character positions instead, use cut.

1

the cut option

echo I have a nice car | cut -d\  -f2,4
have nice

where

  • -d' ' tell cut to use white space instead of tab
  • -f2,4 get 2nd and 4th field
  • Perhaps -d' ' would be a little clearer than -d\ – roaima Sep 15 '15 at 13:53

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.