Computing.Net > Forums > Unix > How to rename a file based 1st line

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Click here to start participating now! Also, check out the New User Guide.

How to rename a file based 1st line

Reply to Message Icon

Name: VivRichards
Date: April 29, 2008 at 09:45:05 Pacific
OS: AIX
CPU/Ram: 6
Comment:

I like to rename a file based on the first line. Here is an example of what I need to do.

File: 034568.dat has 2000 lines with first line as
HIOSPAD23409JHK90000
I like to extract 3 characters from 5th column and rename the file to PAD_034568.dat.


Really appreciate your help.
Viv



Sponsored Link
Ads by Google

Response Number 1
Name: nails
Date: April 29, 2008 at 11:18:19 Pacific
Reply:

When you're sure it works, change 'cp' to 'mv':


#!/bin/ksh

# no error checking
myfile=034568.dat
prevar=$(head -1 "$myfile"| cut -c5-7)

cp "$myfile" "${prevar}_${myfile}"


0

Response Number 2
Name: VivRichards
Date: April 29, 2008 at 11:39:41 Pacific
Reply:

Thanks for your response, being a UNIX novice I have another Q related to this...

Now if I want to put this into a script to execute against unknown filename(s), how would I accomplish that?!

Thanks


0

Response Number 3
Name: nails
Date: April 29, 2008 at 13:55:07 Pacific
Reply:

Consider this:


#!/bin/ksh

# UNTESTED
cd /your/directory
for myfile in $*
do
if [[ -f $myfile ]]
then
prevar=$(head -1 "$myfile"| cut -c5-7)
cp "$myfile" "${prevar}_${myfile}"
fi
done

The above script changes to a /your/directory. That's where your files are.

If your script is called x.ss, execute it with your file names:

x.ss 034568.dat file2.dat file3.dat

if the file exists, it executes the commands.


0

Response Number 4
Name: ghostdog
Date: April 30, 2008 at 00:06:22 Pacific
Reply:


awk 'FNR==1{
cmd = "mv "FILENAME" "substr($0,5,3)"_"FILENAME
system(cmd)
}' *.dat


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More


How 2 find java script us... Need to know about jar



Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Unix Forum Home


Sponsored links

Ads by Google


Results for: How to rename a file based 1st line

renaming a file based on systm date www.computing.net/answers/unix/renaming-a-file-based-on-systm-date/4875.html

How to parse a file of 199 col? www.computing.net/answers/unix/how-to-parse-a-file-of-199-col/7250.html

How to delete a file named -x www.computing.net/answers/unix/how-to-delete-a-file-named-x/3350.html