Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the first 5 characters from each line in shell script

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?

like image 457
user2622247 Avatar asked Jan 07 '14 11:01

user2622247


People also ask

How do you display the first 10 characters from each line of a file?

Using the head Command The head command is used to display the first lines of a file. By default, the head command will print only the first 10 lines.

How do you get the first 3 characters of a string in Unix?

To access the first n characters of a string, we can use the (substring) parameter expansion syntax ${str:position:length} in the Bash shell. position: The starting position of a string extraction. length: The number of characters we need to extract from a string.

How do I print the first 5 lines in Linux?

To print the first n lines, we use the -n or --lines option with the head command as shown below. Suppose we want to display four lines of the text. txt file then we have to execute the command as shown below. To print lines between m and n, we use the head and tail command in the Linux system as shown below.


2 Answers

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" 
like image 80
fedorqui 'SO stop harming' Avatar answered Oct 02 '22 14:10

fedorqui 'SO stop harming'


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 
like image 29
tuxdna Avatar answered Oct 02 '22 12:10

tuxdna