get the first 5 characters from each line in shell script
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"
Well, its a one-liner cut -c-5 sample.txt
. Example:
$ cut -c-5 sample.txt
31113
31114
31111
31112
From there-on, you can pipe it to any other script or command:
$ cut -c-5 sample.txt | while read line; do echo Hello $line; done
Hello 31113
Hello 31114
Hello 31111
Hello 31112