0

I have a variable like

date="January 01 2019"

I want to split it into different variables like

month=$(echo $date|awk '{print $1}')

only I want to simplify it by doing this operation just using bash functionality. Is there any way to do it? I can tell bash to only print, say, the first 3 characters of the variable

month=${date: 0: 7}

which would not work for other months.
Is there any way to do this?

M. Twarog
  • 2,418
  • 3
  • 21
  • 39
Tomas Hrubovcak
  • 316
  • 2
  • 10

2 Answers2

2

You could try following. To get 1st part of your variable.

echo ${date%% *}

From man bash page:

${parameter%word} ${parameter%%word} Remove matching suffix pattern. The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the %'' case) or the longest matching pattern (the%%'' case) deleted. If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • 1
    nice. can you please explain the logic behind this? how can it be applied on printing other columns? – Tomas Hrubovcak Oct 17 '19 at 12:08
  • @TomasHrubovcak, Your welcome, this is called parameter expansion. `%` is for shortest match and `%%` is for the longest match to be deleted from given pattern. – RavinderSingh13 Oct 17 '19 at 12:11
1

Yes. It's possible. If you are sure there are no leading spaces.

$ date="January 01 2019"
$ echo ${date/%\ */}
January

manual

scrot

' \ * - means replace space01 2019 with nothing and print.

Akhil
  • 912
  • 12
  • 23