Result of 'cut' into variable

Hello,

I would like to have a result of a cut-command in a variable.

The file "t.dat" has the following content:

Company                 001.239879123.OB1X.672W12.STS                    UNOLD.001.02

My bash-script:

Header=""
Header=$(cut -c1-160 t.dat | head -1)
echo $Header

The result:

Company 001.239879123.OB1X.672W12.STS UNOLD.001.02

Where are the spaces between the values?

And more important - what do I have to do to get the whole record into the variable "Header"?

Tx in advance.

CU,
API

Hello API,

Welcome to the forum.
I can see there are only 85 characters present in the line as follows.

echo "Company                 001.239879123.OB1X.672W12.STS                    UNOLD.001.02" | awk '{print length($0)}'

Output is as follows.

85
So kindly let us know your complete requirement so that we can help you.

EDIT: Seems you have modified the post now. If you want to take the complete line into a variable then I don't think that there is a need of using cut
command there. If you want to work on lines of a file you can use while loop it will read file line by line and you can perform your operation as per your requirement.

Posted by Makarand Dodmis:

Hello Makarand:
your solution will not have space in the variable as per user query, user needs the spaces in variable.

Thanks,
R. Singh

try

$ header=`cut -c1-160 t.dat | head -1`
$ echo "$header"
Company                 001.239879123.OB1X.672W12.STS                    UNOLD.001.02
1 Like

They got lost because you didn't quote the variable $Header, try

echo "$Header"
Header=$(head -1 t.dat)

Thanks for your quick reply.

First of all - you are right I had to quote the variable "$Header". Then I will get the whole string with all the spaces in it.

For explanation why I use the "cut". I have to read a file and know if it is a single line with 160 characters or the content of the file is one record and I will need also the first 160 characaters. Therfor I can not use "head".

But thanks for this really easy solution... :slight_smile:

CU,
API

Why not read header <t.dat ?

Hi RudiC,

its because I could have a file with - lets say 10.000 characters. All in one line! And I need 160 characters from the beginning.

If I will do it with read, I would get the whole file - because there is only one line in file.

CU,
API

Not if you use (availability assumed)

read -N160 header <t.dat
1 Like

Interesting, in bash 4 and recent ksh93 this works. In bash 3 there is only the -n option which reads bytes, not characters..

But for this purpose it should also have the -r option and not skip leading space, so:

IFS= read -rN 160 header <t.dat
1 Like

Thanks for this.

You are right. This also works...

read -N160 header <t.dat

For info I am using GNU Bash 4.2.45.