Pages

Tuesday, April 13, 2010

Parsing files and rename ...

Sometimes you have to rename files.
This can be tiring when we do it manually.
Command "sed" may be helpful in this case.
I'll take a simple example. I will create a working directory called "work."
We have to create files with the command:
for (( i=1; i<10; i++ )); do echo data$i > data[$i]x[$i].txt;done

The result should be :
$ ls
data[1]x[1].txt  data[3]x[3].txt  data[5]x[5].txt  data[7]x[7].txt  data[9]x[9].txt
data[2]x[2].txt  data[4]x[4].txt  data[6]x[6].txt  data[8]x[8].txt

Try these commands to parse and rename files:
$ for i in  *[]x[]*; do mv -v "$i" "$(echo $i | sed 's/[]x[]//')"; done
`data[1]x[1].txt' -> `data1]x[1].txt'
`data[2]x[2].txt' -> `data2]x[2].txt'
`data[3]x[3].txt' -> `data3]x[3].txt'
`data[4]x[4].txt' -> `data4]x[4].txt'
`data[5]x[5].txt' -> `data5]x[5].txt'
`data[6]x[6].txt' -> `data6]x[6].txt'
`data[7]x[7].txt' -> `data7]x[7].txt'
`data[8]x[8].txt' -> `data8]x[8].txt'
`data[9]x[9].txt' -> `data9]x[9].txt'
[work@test work]$ for i in  *[]x[]*; do mv -v "$i" "$(echo $i | sed 's/[]x[]//')"; done
`data1]x[1].txt' -> `data1x[1].txt'
`data2]x[2].txt' -> `data2x[2].txt'
`data3]x[3].txt' -> `data3x[3].txt'
`data4]x[4].txt' -> `data4x[4].txt'
`data5]x[5].txt' -> `data5x[5].txt'
`data6]x[6].txt' -> `data6x[6].txt'
`data7]x[7].txt' -> `data7x[7].txt'
`data8]x[8].txt' -> `data8x[8].txt'
`data9]x[9].txt' -> `data9x[9].txt'
[work@test work]$ for i in  *[]x[]*; do mv -v "$i" "$(echo $i | sed 's/[]x[]//')"; done
`data1x[1].txt' -> `data1[1].txt'
`data2x[2].txt' -> `data2[2].txt'
`data3x[3].txt' -> `data3[3].txt'
`data4x[4].txt' -> `data4[4].txt'
`data5x[5].txt' -> `data5[5].txt'
`data6x[6].txt' -> `data6[6].txt'
`data7x[7].txt' -> `data7[7].txt'
`data8x[8].txt' -> `data8[8].txt'
`data9x[9].txt' -> `data9[9].txt'
[work@test work]$ for i in  *[]x[]*; do mv -v "$i" "$(echo $i | sed 's/[]x[]//')"; done
`data1[1].txt' -> `data11].txt'
`data2[2].txt' -> `data22].txt'
`data3[3].txt' -> `data33].txt'
`data4[4].txt' -> `data44].txt'
`data5[5].txt' -> `data55].txt'
`data6[6].txt' -> `data66].txt'
`data7[7].txt' -> `data77].txt'
`data8[8].txt' -> `data88].txt'
`data9[9].txt' -> `data99].txt'
[work@test work]$ for i in  *[]x[]*; do mv -v "$i" "$(echo $i | sed 's/[]x[]//')"; done
`data11].txt' -> `data11.txt'
`data22].txt' -> `data22.txt'
`data33].txt' -> `data33.txt'
`data44].txt' -> `data44.txt'
`data55].txt' -> `data55.txt'
`data66].txt' -> `data66.txt'
`data77].txt' -> `data77.txt'
`data88].txt' -> `data88.txt'
`data99].txt' -> `data99.txt'

This is just a simple example ...