Computing.Net > Forums > Unix > Shell Script to copy part of a string

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

Shell Script to copy part of a string

Reply to Message Icon

Name: novice82
Date: September 10, 2009 at 05:03:00 Pacific
OS: Sun Solaris
Subcategory: General
Tags: solaris, linux
Comment:

I have an input file which has rows of numerical digits ( close to 2000 rows )
I want to extract out " the second to the eight digit from the right" of every row of the numeric string into a separate file, with the result separated by a comma as shown.


Example:
00000000000001303275310752
00000000000001827380519015
00000000000000800081610361
00000000000000449481894004
00000000000000449481894004
00000000000001812612607514

Expected result: newfile.txt

7531075,
8051901,
8161036,
8189400,
8189400,
1260751,


I'm guessing something like 'sed' can be used to solve my problem, but i'm not quite sure how to go about achieving this.
Appreciate if someone can guide me with a brief explanation.

regards,

novice.



Sponsored Link
Ads by Google

Response Number 1
Name: nails
Date: September 10, 2009 at 11:29:24 Pacific
Reply:

The Unix cut command should do what you want:

#!/bin/ksh

while read line
do
   length=${#line}   # get the line length
   f1=$(echo "$line"|cut -c$(($length-7))-$(($length-1)) ) # cut out the required columns
   printf "%s,\n" "$f1"
done < datafile.txt > newfile.txt


0

Response Number 2
Name: novice82
Date: September 10, 2009 at 23:32:15 Pacific
Reply:

Thanks mate.

I got around my problem with the following :

cut -c19-25 input.txt | sed 's/$/,/' > temp.txt


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More






Use following form to reply to current message:

Login or Register to Reply
LoginRegister


Sponsored links

Ads by Google


Results for: Shell Script to copy part of a string

Shell Script to find position of su www.computing.net/answers/unix/shell-script-to-find-position-of-su/6358.html

Script to scan files for a string www.computing.net/answers/unix/script-to-scan-files-for-a-string/7532.html

shell script www.computing.net/answers/unix/shell-script-/7655.html