Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to cut last 4 characters in file using shell script 1

Status
Not open for further replies.

eb222

MIS
Mar 12, 2007
11
NL
hi

if i have a file i wanted to cut the last 4 digits in a shell script -how do i do it?

e.g

>>file.sh 123456.zip

>>vi file.sh

FILENAME=$1
DIRNAME=$1 --need this without the .zip extention

how do i do this??

Thanks






 
Have a look at the basename command:
DIRNAME=`basename $1 .zip`

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
Hi

You did not specified what kind of shell it is, but this works with [tt]bash[/tt] and (pd)[tt]ksh[/tt] :
Code:
[gray]# remove zip extension[/gray]
DIRNAME=${FILENAME%.zip}

[gray]# remove any extension[/gray]
DIRNAME=${FILENAME%.*}

Feherke.
 
wsFilePath="/myfile/tmp/ParList.dat"
wsFile=`basename $wsFilePath| cut -d. -f1`

this worked for me.

baseline returns the filename from the full filename and path. This is then piped through cut which splits the string by delimited . (That's the -d.) Field 1 is returned which is the filename. If you wanted the extension then that would be field 2 (-f2).

echo $wsFile
ParList
 
Hi

Ok, and if the file name contains more than one dots ( . ) ?
Code:
[blue]master #[/blue] wsFilePath="/myfile/tmp/Par.List.dat"

[blue]master #[/blue] wsFile=`basename $wsFilePath| cut -d. -f1`

[blue]master #[/blue] echo "$wsFile"
Par

Feherke.
 
Luckily my file won't contain any more than one dot.

I found some code involving awk, substr and length which I will have a look at and see if I can get it to work.

I'm from a VMS/DCL background and just starting in Unix Shell scripting. This sort of think is really easy in VMS/DCL.

 
line="1234567890abcd"

This command will print out 1234567890

echo $line | awk '{print substr($0,1, length($0)-4)}'


This command will print out 0abcd
echo $line | awk '{print substr($0,length($0)-4)}'

Note:
substr( String, M, [ N ] ) Returns a substring with the number of characters
specified by the N parameter. The substring is taken from the string specified
by the String parameter, starting with the character in the position specified
by the M parameter. The M parameter is specified with the first character in the String parameter as number 1. If the N parameter is not specified, the length of the substring will be from the position specified by the M parameter until the end of the String parameter.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top