68

How to retrieve the first 10 characters of a variable with Bash?

FOO="qwertzuiopasdfghjklyxcvbnm"

I need to get qwertzuiop.

codeforester
  • 34,080
  • 14
  • 96
  • 122
user2093552
  • 809
  • 1
  • 8
  • 12
  • 2
    That isn't correct assignment syntax. `foo=${foo:0:10}` ... `foo=${foo%%"${foo##??????????}"}` – ormaaj Feb 21 '13 at 00:44

2 Answers2

126

If the variable is: FOO="qwertzuiopasdfghjklyxcvbnm"

then

 echo ${FOO:0:10}

will give the first 10 characters.

P.P
  • 112,354
  • 20
  • 166
  • 226
62

Use the head command.

echo $FOO | head -c 10
=> qwertzuiop
pje
  • 20,728
  • 10
  • 53
  • 68
  • I think this answer make the most sense, and works at the end of a long line used to generate the string `FOO`. – Bryson S. Nov 02 '19 at 17:56