cancel
Showing results for 
Search instead for 
Did you mean: 

Print sequence and prefix

syedar
Advisor

Print sequence and prefix

Hi All,

I have a file "MATSX_M_2009042800009352.dat", i just need to print sequence from the file i.e before dot 4 digits and need to print file prefix as "MATSX_M" first 7 characters of file.
Please help me in this issue as iam new to unix.
3 REPLIES
James R. Ferguson
Acclaimed Contributor

Re: Print sequence and prefix

Hi:

Do you mean this?

# X="MATSX_M_2009042800009352.dat"
# echo ${X}|awk '{print substr($0,1,7)substr($0,21,4)}'
MATSX_M9352

Regards!

...JRF...
syedar
Advisor

Re: Print sequence and prefix

Hi JRF,

Thanks for your support.
Matti_Kurkela
Honored Contributor

Re: Print sequence and prefix

You want to pick some components of the file name, right?

Too bad you did not specify exactly how you wish the output formatted...

I assume the length of the filename is fixed? If it isn't, there is a different way for pickign the sequence number, but it is not as clear as using the "cut" command.

A short script can do the job:

#!/bin/sh
for FILENAME in "$@"
do
PREFIX=$( echo "$FILENAME" | cut -c 1-7 )
SEQUENCE=$( echo "$FILENAME" | cut -c 21-24 )
echo "prefix: $PREFIX sequence: $SEQUENCE"
done

Save this script as a text file and give it execute permissions (chmod a+x <scriptname>).
Then you can use it like:

./<scriptname> *.dat

This script can handle an unlimited number of filenames: the effective limit is the maximum length of the command line. Wildcards are not a problem either (as they are a feature of the shell, not of the script).

The script will produce one line of output for each name listed on the command line.
If you want to change the format of the output line, simply edit the "echo" line of the script.

MK
MK