get the first 5 characters from each line in shell script get the first 5 characters from each line in shell script bash bash

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/bashfilename='sample.txt'while read -r linedo  id=$(cut -c-5 <<< "$line")  echo $id  #code for passing id to other script file as parameterdone < "$filename"


Well, its a one-liner cut -c-5 sample.txt. Example:

$ cut -c-5 sample.txt 31113311143111131112

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; doneHello 31113Hello 31114Hello 31111Hello 31112


Rather than piping echo into cut, just pipe the output of cut directly to the while loop:

cut -c 1-5 sample.txt |while read -r id; do  echo $id  #code for passing id to other script file as parameterdone