i did a script that retrieve content of a source file so i can create a target file the way i want it.
I do a "sed" command so i can change the word "Numérique" with "PIC S".
Source File .txt :
MotifRad;CHAR(2);Motif de radiation
MtPrime;Numérique 8.2;Montant prime d'origine
Target File .txt :
* Motif de radiation
05 MotifRad PIC X(2).
* Montant prime d'origine
05 MtPrime PIC S 8.2.
As you can see i did change the word "Numérique" but i'd like to add the number that follows in parentheses like that : PIC S (8.2), how could i do that ?
Bash script :
#!/bin/bash
#Fichier Source
fichier="APGFPOLI.des.txt"
champAdd="05 "
if [[ -f "$fichier" ]]
then
# read it
sed 1d $fichier| sed -i 's/CHAR/PIC X/' $fichier | sed -i 's/Numérique/PIC S/' $fichier | while IFS=';' read -r nomChamp format libelle
do
echo \* $libelle
echo $champAdd $nomChamp $format.
done <"$fichier" > test.txt
fi
CodePudding user response:
$ sed 's/;Numérique[[:space:]]\ \([^;]*\)/;PIC S(\1)/' <<< "MtPrime;Numérique 8.2;Montant prime d'origine"
MtPrime;PIC S(8.2);Montant prime d'origine
Or, with GNU sed:
$ sed -E 's/;Numérique\s ([^;]*)/;PIC S(\1)/' <<< "MtPrime;Numérique 8.2;Montant prime d'origine"
MtPrime;PIC S(8.2);Montant prime d'origine
Applied to your file:
$ sed -E '/Numérique/s/;Numérique\s ([^;]*)/;PIC S(\1)/' file.txt
MotifRad;CHAR(2);Motif de radiation
MtPrime;PIC S(8.2);Montant prime d'origine
If you want to replace CHAR
and Numérique
in the same run:
$ sed -E '/CHAR/s/;CHAR(\([[:digit:]] \));/;PIC X\1/
/Numérique/s/;Numérique\s ([^;]*)/;PIC S(\1)/' file.txt
MotifRad;PIC X(2);Motif de radiation
MtPrime;PIC S(8.2);Montant prime d'origine
CodePudding user response:
I am only answering the portion regarding the replacement of Numérique [a floating point number]
with PIC S [that same floating point number]
.
Use a capturing group to capture the floating point and a back reference to add it back to the replacement:
cat file
MotifRad;CHAR(2);Motif de radiation
MtPrime;Numérique 8.2;Montant prime d'origine
sed -E 's/Numérique([[:blank:]] [[:digit:].] )/PIC S\1/' file
MotifRad;CHAR(2);Motif de radiation
MtPrime;PIC S 8.2;Montant prime d'origine
If you want parenthesis around the replacement:
sed -E 's/Numérique([[:blank:]] )([[:digit:].] )/PIC S\1(\2)/' file
MotifRad;CHAR(2);Motif de radiation
MtPrime;PIC S (8.2);Montant prime d'origine
Capturing groups are defined with ([thing to capture])
and the reference to that captured item is \1
, \2
, \n
with the left most opening parenthesis being the lowest number and so on.
Example:
echo 'this;that' | sed -E 's/(.*);(.*)/\2 \1/'
that this