LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Scripting - reduce output from grep to first 8 characters (https://www.linuxquestions.org/questions/linux-newbie-8/scripting-reduce-output-from-grep-to-first-8-characters-854347/)

abbotslad 01-05-2011 08:23 AM

Scripting - reduce output from grep to first 8 characters
 
Hi there
I have file.txt - a database with 2 fields. Each line contains
1) a reference number (4 digit integer)
then a full-stop to seperate the 2 fields
2) A string name

eg

0234. abcsefset
0567. bcfsdfse

I am using a bash shell script to select each line in turn, and output the reference number:

Code:

#!/bin/sh

echo Starting...

record=0
cat file.txt | while read LINE ;
do
        record=$((record+1))
        ref="$LINE"
        echo "$ref"
done

Which iterates through the database, but prints the whole line. I only want to print the first 4 digits, is there any way you can use the cut command to cut off the full stop and string on each line?

acid_kewpie 01-05-2011 08:28 AM

of course there is. echo $ref | cut -c -4

aggrishabh 01-05-2011 08:45 AM

you can use awk command for this awkis a very powerful command.

awk -F '.' '{print $1}' file_name

Hope this will help.

abbotslad 01-05-2011 09:24 AM

Thanks - one more quick question - if I want to store this output (4 digit number) as a variable, what syntax would I use?

grail 01-05-2011 09:31 AM

You already have it one variable, but to store in another is just as easy:
Code:

ID=${LINE%.*}

crts 01-05-2011 09:32 AM

Quote:

Originally Posted by abbotslad (Post 4214041)
Thanks - one more quick question - if I want to store this output (4 digit number) as a variable, what syntax would I use?

Command substitution. E.g.
Code:

variable=$(echo $ref | cut -c -4)

crts 01-05-2011 09:35 AM

Quote:

Originally Posted by grail (Post 4214049)
You already have it one variable, but to store in another is just as easy:
Code:

ID=${LINE%.*}

Oops, I should have read the entire initial post. Of course, this is a more efficient solution than command substitution :)
@OP: Use grail's solution.


All times are GMT -5. The time now is 04:04 AM.