PDA

View Full Version : [Solved] i need awk help


graudeejs
February 13th, 2009, 11:41
I did an sh script mistake....
now some of my files and directories start and end with "2"

How can i remove 2 from them with awk.

1) it should check if 1st and last chr is "2"
2) modify string [cut middle of it]
3) rename to normal file name


I'm awk NOOB, please help

Thanks in advance

P.S.
If you can do it with perl [which i don't know at all], or somehow else, please post....
I accept anything that can fix this

ale
February 13th, 2009, 12:10
QND
ls -1 2*2 | while read OLD; do
NEW="$( echo "$OLD" | sed 's/^2//' | sed 's/2$//' )"
echo mv "$OLD" "$NEW"
done
Obviously you have to remove the echo in the 3rd line.

DutchDaemon
February 13th, 2009, 12:18
Or:

ls -d 2*2 | while read file; do newfile=$(echo $file | sed 's/^2//' | sed 's/2$//'); cp -Rp $file $newfile; done

(using copy for safety AND treating files and directories alike)

graudeejs
February 13th, 2009, 14:01
this is what i came up, after your posts

#!/bin/sh

dir=`pwd`

fix() {
ls -1 -d "$1/"2*2 | while read OLD; do
NEW="$( echo $(basename "$OLD") | sed 's/^2//' | sed 's/2$//' )"
if [ "$OLD" != "$NEW" ]; then
mv "$OLD" "$1/$NEW"
if [ -d "$1/$NEW" ]; then fix "$1/$NEW"; fi
fi
done
}

fix "$dir"

exit 0

Thanks to bought of you

lme@
February 20th, 2009, 11:42
If you don't mind using bash, there is no need for any other program like sed / awk / $foo at all.


#!/usr/local/bin/bash

dir=$YOURDIR

cd $dir
for element in *; do
[ ${element:0:1} = "2" -a ${element: -1} = "2" ] && mv ${element} ${element:1:${#content}-2}
# ^^^ One char ^^^ one char ^^^ from char 1 to the second last
# from the beginning from the end


done


This can be faster than the other solutions if there are a lot of files involved and you need to spawn some seds and awks for every file.

ephemera
February 21st, 2009, 17:05
If there are no 2's in the original files you could do:

ls -1 2*2 | awk -F2 '{printf "mv %s %s\n",$0,$2}' | sh

s0xxx
April 15th, 2009, 17:21
I know the thread has been solved, but a few thoughts:
QND
ls -1 2*2 | while read OLD; do
NEW="$( echo "$OLD" | sed 's/^2//' | sed 's/2$//' )"
echo mv "$OLD" "$NEW"
done
Obviously you have to remove the echo in the 3rd line.
Maybe shorten the code, and call sed once only with:
$ ls
2iaus2 2ii 2oo2

$ ls 2*2
2iaus2 2oo2

$ ls 2*2 | sed -e 's/\(^2\(.*\)2$\)/mv \1 \2/g'| sh

$ ls
2ii iaus oo

# Or using a -r switch for readability:
# ls 2*2 | sed -re 's/(^2(.*)2$)/mv \1 \2/g'| sh

Another possible aproach (but it does strip 2's even if matched on one side only):
$ ls -l | awk '{print $9}' | \
while read line; do \
filename=${line##2} && echo ${filename%%2}; done
This could be improved also of course. ;)