get the first 5 characters from each line in shell script

user2622247 picture user2622247 · Jan 7, 2014 · Viewed 53.5k times · Source

Here is my sample.txt file it contains following

31113    70:54:D2 - a-31003
31114    70:54:D2 - b-31304
31111    4C:72:B9 - c-31303
31112    4C:72:B9 - d-31302

I have to write the shell script in that I am passing first 5 characters (eg 31113) as input id to other script. For this I have tried this

#!/bin/sh
filename='sample.txt'
filelines=`cat $filename`
while read -r line
do
  id= cut -c-5 $line
  echo $id
  #code for passing id to other script file as parameter
done < "$filename"

but it is not working this gives me error as

cut: 31113: No such file or directory
cut: 70:54:D2 No such file or directory
31114
31111
31112
: No such file or directory

How can I do this?

Answer

If you want to use cut this way, you need to use redirection <<< (a here string) like:

var=$(cut -c-5 <<< "$line")

Note the use of var=$(command) expression instead of id= cut -c-5 $line. This is the way to save the command into a variable.

Also, use /bin/bash instead of /bin/sh to have it working.


Full code that is working to me:

#!/bin/bash

filename='sample.txt'
while read -r line
do
  id=$(cut -c-5 <<< "$line")
  echo $id
  #code for passing id to other script file as parameter
done < "$filename"