2

Let's say I have a file like this :

14-Hello14657
156:Good morning 487
1478456=Good bye 1 2

I would like to extract the first character after the first number of the line (and store it in a variable, one at a time). In this example, it would extract

-
:
=

I guess that I should probably use regular expressions but I am still learning it and I can't find a way to do this.

Whin3
  • 675
  • 2
  • 9
  • 27

2 Answers2

3

sed approach:

s="156:Good morning 487"
var1=$(sed 's/^[0-9]*\([^0-9]\).*/\1/'  <<< $s)
echo $var1
:

Another approach is bash variable expansion + cut command:

s="1478456=Good bye 1 2"
echo ${s//[[:digit:]]/} | cut -c1
=
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
1

With GNU grep (the one installed on most Linux systems) you can use

grep -Po '^[0-9]+\K.' yourFile

To store the output in a variable, use

myVar="$(grep -Po '^[0-9]+\K.' yourFile)"

Using your example, the variable myVar will contain all three symbols:

-
:
=
Socowi
  • 25,550
  • 3
  • 32
  • 54
  • Is there a equivalent working with every grep version ? – Whin3 May 03 '17 at 08:22
  • As far as I know: No. But you can use `perl -nle 'print $& if m{^[0-9]+\K.}'` as described in [this answer](http://stackoverflow.com/a/16658690/6770384). – Socowi May 03 '17 at 08:28