Parse and replace string in filename

Hi,

I've a filename of this format: "XXX_XXX_TXT.TAR.AS". Need to change the name into this format: "XXX_XXX.TAR.AS". This file resides in a directory. I'm ok with using the find command to search and display it.

Essentially I just need to replace the string "_TXT.TAR.AS" to ".TAR.AS". Is awk or sed the way to do it?

Thanks.

[quote=chengwei;302199456]
Hi,

I've a filename of this format: "XXX_XXX_TXT.TAR.AS". Need to change the name into this format: "XXX_XXX.TAR.AS". This file resides in a directory. I'm ok with using the find command to search and display it.

Essentially I just need to replace the string "_TXT.TAR.AS" to ".TAR.AS". Is awk or sed the way to do it?

Thanks.[/QUOTE
first do a find and store the files in a new file. Loop it and inside loop do this.

sed 's/XXX_XXX_TXT.TAR.AS/XXX_XXX.TAR.AS/' filename 

With sed:

sed 's/\(.*\)_TXT\(.*\)/\1\2/'

With awk:

awk '{sub("_TXT","")}1'

Regards

The values XXX_XXX are actually timestamp dynamically generated, hence I do not know them in advance. How would I be able to combine with the find command to achieve this?

I did this:

find . -name "*_TXT.TAR.AS" -print -exec awk '{sub("_TXT.TAR.AS")}1' {} \;

and gotten the error messages:

What am I missing here?

Many thanks for the help.

find . -name "*_TXT.TAR.AS" -print|awk '{f=$0;sub("_TXT","");print "mv "f" "$0}'|sh

or:

find . -name "*_TXT.TAR.AS" -print |sed 's/\(.*\)_TXT\(.*\)/mv & \1\2/'| sh

Check the output before you pipe it to sh.

Regards

What does the "1" in awk command meant? How does it change into the string that I want?

Thanks!

Tried this,

Made a mistake with my initial post. What I need was actually to change from "_TXT.TAR.AS" to ".ZIP.AS".

find . -name "*_TXT.TAR.AS" -print|awk '{f=$0;sub("_TXT.TAR",".ZIP");print "mv "f" "$0}'|sh

Regards

I encountered:

So I used this instead and its working.

find . -name "*_TXT.TAR.AS" -print | sed 's/\(.*\)_TXT.TAR.AS/\1.ZIP.AS/' >> rmfile

But now my problem is that the first line in the file rmfile is:

I need to change it into:

Could you help?

Thanks!

Use nawk or /usr/xpg4/bin/awk on Solaris.

I'm able to get it done with sed but need to change from:

./XXXX.ZIP.AS

to

rm /home/dms/XXXX.ZIP.AS

How could I do this?

You can remove the files with this sed command:

find . -name "*_TXT.TAR.AS" -print|sed 's/\(.*\)_TXT.TAR.AS/mv & \1.ZIP.AS/' | sh

Regards

Thanks! Got it. :smiley:

hi!

i tried using this method to parse a filename, but i had no success. can anyone help me figure out how to parse this filename?

fmc_000.bshort

just looking to get the number, 000.

thanks in advance!

Something like this maybe?

number=`echo "$filename" | tr -dc 0-9`

We can't guess from a single filename how to generalize for your particular situation, but the above should work for anything with a single number in the middle.

# a=fmc_000.bshort
# a=${a#*_}
# echo ${a%.*}
000

Another...

echo fmc_000.bshort | awk -F"[_|.]" '{print $2}'