2

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?

1
  • 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). Sep 14, 2015 at 20:38

4 Answers 4

6

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

2
  • 1
    If you're going to use the split+glob operator, you should disable the glob part which you don't want here. Sep 15, 2015 at 6:23
  • 1
    On shells without arrays, you can do set -f; unset IFS; set -- $line and have the words in $1, $2... Sep 15, 2015 at 16:07
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
1
  • Perhaps -d' ' would be a little clearer than -d\ Sep 15, 2015 at 13:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .