Need help on getting the first few characters of a file.

Friends ,
I need some help in writing a shell script to get the first few characters from a file for all the lines in that file.

Here is sample data inthe file.

9 JACOBS 0175 
10 VENDOR_0175 
11 JACOBS 0175 
100 0175

I want the ouput as

9,10,11,100

It doesn't have any fixed length,the only thing I can say is the first I need all the caracters until it first hits 2 spaces from each line in the file.

$ cut -f1 -d\  file1 | paste -sd, -
9,10,11,100
1 Like
#!/bin/ksh or dash
# first
while read one xstr
do
     printf "%s," $one
done
echo

Using example:

chmod a+rx first
cat somefile | ./first  > result.txt
1 Like

Scott ,
It worked awesome.
Thanks you so much .
But, can you please explain what exactly the syntax means?

Hi.

Perhaps this is a bit clearer:

cut -f1 -d" " file1 | paste -sd, -

It "cuts" the first field (-f1) from the file file1 using a delimeter of space (-d" "), then pipes this to the paste command which concatenates (-s) the lines together with a delimeter of a comma (-d,) using the file - (standard input) (i.e. the output of the cut command).

1 Like
$
$ cat f6
9 JACOBS 0175
10 VENDOR_0175
11 JACOBS 0175
100 0175
$
$ awk '{x = x","$1} END{print substr(x,2)}' f6
9,10,11,100
$

tyler_durden

1 Like

suppose ' abc ' is the file name containing all the data then

cut -d" " -f1 abc |n paste -s d","
echo $(sed -e 's/^\([0-9]*\).*$/\1,/' -e '$s/,$//' file) | sed 's/ //g'
9,10,11,100