1

I would like to subsitute in a txt file the followings targets for example

"code_000040" by "code_40" and "code_067340" by "code_67340" and so on..,

in other words to remove the zeros in the 6 number ids before the real numbering id starts

Plaese any help!!

2 Answers2

1

The easiest way is to use sed:

for file in code_*; do
  newname=$(echo $file | sed 's/_0*/_/')
  mv "$file" "$newname" #you may want to use -i to avoid accidents
done

I usually write this out in one line.

The outer loop can be anything: a for loop with a glob as above, a list of files, or even a find command piped into while read;

orion
  • 41
  • do you mean something like the following in linux in one line?

    for filename in code_; do newname=$(echo $filename | sed 's/_0/_/')

    – user61677 Mar 03 '14 at 12:02
  • @user61677 exactly, just continue the line, adding semicolons between commands (in separate lines semicolons are optional, but in one line you need them). Or you can even do something like for filename in code_; do mv "$filename" "$(echo $filename | sed 's/_0/_/')"; done

    That the quotes are there for safety in case you have spaces or some other strange characters in the filenames.

    – orion Mar 03 '14 at 13:26
  • This changes the file's name, not its contents. @user61677 is that what you want or do you want to replace text inside the file? – terdon Mar 03 '14 at 15:45
1

If you want to replace the text within the file, with GNU sed, you could do:

sed -i 's/code_0*\([0-9]\)/code_\1/g' file.txt

or

perl -i -pe 's/code_0+(\d+)/code_$1/g' file.txt

That will modify the original file, remove the -i to keep the file unchanged or give an argument to -i to create a backup file (this will create a copy of the original called file.txt.bak):

perl -i.bak  -pe 's/code_0+(\d+)/code_$1/g' file.txt
terdon
  • 242,166