Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to shorten a string

Let's say I have following files: 1.html, 2.html and 3.html and I want to rename them to 1.html-bak, 2.html-bak and 3.html-bak. To do this I run following command:

find . -name '*.html' -print0 | xargs -0 -I {} mv {} {}-bak

Everything is OK, files are renamed as expected.

The question is how to rename them back to *.html instead of *.html-bak?

How to remove last 4 chars from string?

like image 813
k4h Avatar asked Jan 10 '23 18:01

k4h


2 Answers

You can use ${file%-*} to get the desired file name back. The following code loops through all files whose name end with html-bak and performs the renaming by removing everything after the last dash:

for file in *html-bak
do
   echo "mv $file ${file%-*}" # <-- using "echo" for safety. Remove once checked
done

${var%-*} strips the shortest match of * from back of $var. That is, removes until the first dash - is found starting from the right:

$ file="1.h-tml-bak"
$ echo ${file%-*}
1.h-tml

You of course could also use the length, to get everything but the last 4 characters:

$ echo ${file:0:-4}
1.h-tml
like image 92
fedorqui 'SO stop harming' Avatar answered Jan 18 '23 07:01

fedorqui 'SO stop harming'


If you have GNU Parallel you can run:

find . -name '*.html-bak' -print0 | parallel -0 mv {} {.}.html

This works even if the filenames contain ', " and space.

All new computers have multiple cores, but most programs are serial in nature and will therefore not use the multiple cores. However, many tasks are extremely parallelizeable:

  • Run the same program on many files
  • Run the same program for every line in a file
  • Run the same program for every block in a file

GNU Parallel is a general parallelizer and makes is easy to run jobs in parallel on the same machine or on multiple machines you have ssh access to.

If you have 32 different jobs you want to run on 4 CPUs, a straight forward way to parallelize is to run 8 jobs on each CPU:

Simple scheduling

GNU Parallel instead spawns a new process when one finishes - keeping the CPUs active and thus saving time:

GNU Parallel scheduling

Installation

A personal installation does not require root access. It can be done in 10 seconds by doing this:

(wget -O - pi.dk/3 || curl pi.dk/3/ || fetch -o - http://pi.dk/3) | bash

For other installation options see http://git.savannah.gnu.org/cgit/parallel.git/tree/README

Learn more

See more examples: http://www.gnu.org/software/parallel/man.html

Watch the intro videos: https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1

Walk through the tutorial: http://www.gnu.org/software/parallel/parallel_tutorial.html

Sign up for the email list to get support: https://lists.gnu.org/mailman/listinfo/parallel

like image 32
Ole Tange Avatar answered Jan 18 '23 07:01

Ole Tange