1

I have file name like "FAI_4O57A" which has always three alphabets followed by underscore and than variable length digits from 1-7 (lenght) followed by single Alphabet.

I want to extract the first four characters and than replace the other digits with my own numbers like 000001 than 000002 and so on. (To auto number the file names.).

How to do this using awk. or sed. Any help will be appreciated. Thanks.

AKK
  • 51
  • 6

2 Answers2

2

One way with awk:

awk '{cnt=sprintf("%06d", ++s);$1=substr($1,1,4) cnt}1' inputFile
jaypal singh
  • 74,723
  • 23
  • 102
  • 147
1

Try doing this :

rename -n '$c++; s/^(.{4}).*/sprintf("%s%05d", $1, $c)/e' [A-Z][A-Z][A-Z]_*

You need the perl's rename, see this

Remove the -n switch when your tests are OK (dry run mode).

Ex. :

$ ls -1
DEF_FAI_4O58A
FAI_4O57A
FTH_4O59A
box.py
index.html
robots.txt
test.html

$ rename -n '$c++; s/^(.{4}).*/sprintf("%s%04d", $1, $c)/e' [A-Z][A-Z][A-Z]_*
DEF_FAI_4O58A -> DEF_0001
FAI_4O57A -> FAI_0002
FTH_4O59A -> FTH_0003

If you really want to do it :

printf '%s\n' [A-Z][A-Z][A-Z]_*  |
    awk '{c++; printf("%s%04d\n", substr($1, 0, 4), c)}' 

Edit :

if you need to treat columns in YOUR_OWN_FILE :

rename -n '$c++; s/^(.{4}).*/sprintf("%s%04d", $1, $c)/e' $(awk '{print $2}' YOUR_OWN_FILE)
Community
  • 1
  • 1
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • I have 2 columns in a file and the Ist coummns contains file name and second column absolute path of file. eg. FAE_12A home/users/some_direcotry/FAE_12A.wav How should I change the above format for Ist columnn Thanks, – AKK Jun 20 '13 at 18:57
  • In a _file_ or in the _file name_ ? – Gilles Quénot Jun 20 '13 at 19:02
  • In a text file 2 columns, Ist column filename and second column path_to_file. – AKK Jun 20 '13 at 19:05