-
BATCH > manipuler les chaines de caractères
ALIGNER DU TEXTE
aligner à droite
l’astuce est d’ajouter un grand nombre d’espace, puis de n’afficher que les 8 derniers caractères :
set x=3000 set y=2 set x= %x% set y= %y% echo.X=%x:~-8% echo.Y=%y:~-8%
résultat :
X= 3000 Y= 2
AFFICHER DES CARACTÈRES
afficher les premiers caractères
:~debut,longueurset str=abcdefghi set str=%str:~0,4%
résultat :
abcd
afficher les derniers caractères
Map and Lookup - Use Key-Value pair list to lookup and translate values
name of a month into it`s corresponding two digit number. The key-value pairs are listed in the map variable separated by semicolon. Key and value itself are separated by one dash character. Same can be used to tranlate a day-of-the-week short string into a day-of-the-week long string by changing the map content only.
REM ---- Ex 1: name of month into two digit number ---- SET v=Mai SET map=Jan-01;Feb-02;Mar-03;Apr-04;Mai-05;Jun-06;Jul-07;Aug-08;Sep-09;Oct-10;Nov-11;Dec-12 CALL SET v=%%map:*%v%-=%% SET v=%v:;=&rem.% ECHO.%v% REM ---- Example 2: Translate abbreviation into full string ---- SET v=sun set map=mon-Monday;tue-Tuesday;wed-Wednesday;thu-Thursday;fri-Friday;sat-Saturday;sun-Sunday CALL SET v=%%map:*%v%-=%% SET v=%v:;=&rem.% ECHO.%v%
05 Sunday
Mid String - Extract a Substring by Position
:~ The example here shows how to extract the parts of a date.
echo.Date : %date% echo.Month : %date:~4,2% echo.Day : %date:~7,2% echo.Year : %date:~10,4%
résultat :
Date : 26/03/2018 Month : 26 Day : 03 Year : 2018
supprimer des caractères par substitution
supprimer tous les
foo:set str=abcfoodeffoo set str=%str:foo=%
résultat :
abcdef
SUPPRIMER DES CARACTERES
Enlever les Premier et le Dernier caractères
:~1,-1 enlève le premier et le dernier caractère.
set str=abcdef set str=%str:~1,-1%
résultat :
bcde
Enlever tous les espaces
set str= toto &rem set str=%str: =%
REMPLACER UNE SOUS-CHAINE
Remplacer tous les
fooparbar:set str=abcdefoo123456foo set str=%str:foo=bar%
résultat :
abcdebar123456bar
EXTRAIRE DES CARACTÈRES
derniers caractères
récupère les 4 derniers caractères :
set str=%str:~-4%
Découper une chaine
echo.-- Jour de la semaine
FOR /f %%a IN ("%date%") DO set d=%%a
echo.Date : %date%
echo.d : %d%
echo.echo.-- couper la date grace aux slash et espace comme delimiters
for /f "tokens=1,2,3,4 delims=/ " %%a in ("%date%") do set wday=%%a&set month=%%b&set day=%%c&set year=%%d
echo.Weekday: %wday%
echo.Month : %month%
echo.Day : %day%
echo.Year : %year%
résultat :-- Jour de la semaine Date : Thu 12/02/2005 d : Thu --
couper la date grace aux slash et espace comme delimiters
Weekday: Thu Month : 12 Day : 02 Year : 2005Concaténer
set "str1=Hello" set "str2=World" set "str3=%str1%%str2%" set "str4=%str1% %str2%" echo.%str3% echo.%str4%
résultat :
HelloWorld Hello World
Enlever les espaces du début d’une chaine
Utilser FOR pour enlever les espaces au début d’une variable: str.
set str= 15 espaces echo."%str%" FOR /f "tokens=* delims= " %%a IN ("%str%") DO set str=%%a echo."%str%"
résultat :
" 15 espaces" "15 espaces"
Enlever les guillemets
set str="cmd politic" echo.%str% for /f "useback tokens=*" %%a in ('%str%') do set str=%%~a echo.%str%
résultat :
"cmd politic" cmd politic
Enlever les espaces à la fin d’une chaine
Attention: le module Delayed Expansion doit être activé.
set str=15 espaces &rem echo."%str%" FOR /l %%a IN (1,1,31) DO if "!str:~-1!"==" " set str=!str:~0,-1! echo."%str%"
résultat :
"15 espaces " "15 espaces"
substitution
set str=15 espaces &rem set str=%str%## set str=%str: ##=##% set str=%str: ##=##% set str=%str:##=% echo."%str%"
—
https://www.dostips.com/DtTipsStringOperations.php
https://ss64.com/nt/syntax-substring.html
https://stackoverflow.com/questions/13805187/how-to-set-a-variable-inside-a-loop-for-f
https://stackoverflow.com/questions/10456801/batch-file-equivalent-of-currentdir-pwd
—
Replacing a Substring With Another String in Bash
Replace substring natively in bash (good for a single line)
Bash has some built-in methods for string manipulation. If you want to replace part of a string with another, this is how you do it:
${main_string/search_term/replace_term}
Create a string variable consisting of the line: “I am writing a line today” without the quotes and then replace
today
withnow
:line="I am writing a line today" echo "${line/today/now}" I am writing a line now
Did you understand what just happened? In the syntax
"${line/today/now}"
, line is the name of the variable where I’ve just stored the entire sentence. Here, I’m instructing it to replace the first occurrence of the wordtoday
withnow
. So instead of displaying the contents of the original variable, it showed you the line with the changed word.Hence, the
line
variable hasn’t actually changed. It is still the same:echo $line I am writing a line today
But you can definitely replace the word you want to and modify the same variable to make the changes permanent:
line="${line/today/now}" echo $line I am writing a line now
Now the changes have been made permanent and that’s how you can permanently replace the first occurrence of a substring in a string.
You can also use other variables to store specific substrings that you wish to replace:
replace="now" replacewith="today" line="${line/${replace}/${replacewith}}" echo $line I am writing a line today
Here, I stored the word to be replaced in a variable called
replace
and the word that it would be replaced with insidereplacewith
. After that, I used the same method as discussed above to “revise” the line. Now, the changes I had made in the beginning of this tutorial have been reverted.Let us look at another example:
hbday="Happy Birthday! Many Many Happy Returns!" hbday="${hbday/Many/So Many}" echo $hbday Happy Birthday! So Many Many Happy Returns!
Replacing all occurrences of a substring
You can also replace multiple occurrences of substrings inside strings. Let’s see it through another example:
hbday="${hbday//Many/So Many}" echo $hbday Happy Birthday! So Many So Many Happy Returns!
That extra / after
hbday
made it replace all occurrences ofMany
withSo Many
inside the sentence.Replace string using sed command (can work on files as well)
Here’s another way for replacing substrings in a string in bash. Use the sed command in this manner:
Replace first occurrence:
line=$(sed "s/$replace/s//$replacewith/" <<< "$line")
If I take the first example, it can be played as:
You can also replace all occurrences by adding
g
at the end:line=$(sed "s/$replace/$replacewith/g" <<< "$line")
Now, you may think this is a more complicated than the native bash string method. Perhaps, but sed is very powerful and you can use it to replace all the occurrences of a string in a file.
sed -i 's/$replace/$replacewith/' filename
Sed is a very powerful tool for editing text files in Linux. You should at least learn its basics.
line=$(sed "s/$replace/s//$replacewith/" <<< "$line")
and it should be:
line=$(sed "s/$replace/$replacewith/" <<< "$line")
just like in the screenshot below that.