# i need awk help



## graudeejs (Feb 13, 2009)

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 (Feb 13, 2009)

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 (Feb 13, 2009)

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 (Feb 13, 2009)

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@ (Feb 20, 2009)

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 (Feb 21, 2009)

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 (Apr 15, 2009)

I know the thread has been solved, but a few thoughts:


			
				ale said:
			
		

> QND
> 
> ```
> ls -1 2*2 | while read OLD; do
> ...


Maybe shorten the code, and call sed once only with:

```
$ ls
2iaus2  2ii  2oo2

$ ls 2*2
2iaus2  2oo2

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

$ ls
2ii  iaus  oo

# Or using a -r switch for readability: 
# [b]ls 2*2 | sed -re 's/(^2(.*)2$)/mv \1 \2/g'| sh[/b]
```
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.


----------

