Home > OS >  replace string between two delimiters shell in a certain position in shell
replace string between two delimiters shell in a certain position in shell

Time:10-10

How do I replace a string between two delimiters?

In a line wherestrings are separated by ";" ,I'd like to replace the string in the 3rd position by another string($new_value) The string in the 3rd position can appear multiple times in the same line but it should only be changed in the 3rd position

I've tried

echo $laligne | awk -v repl=${new_value} -F ";" '{ printf("%s;%s;%s;%s;%s",$1,$2,repl,$4,$5)}' >> file.txt

and

old_value=`echo $line | awk '{split($0,a,";");print a[3]}'`
echo $laligne | awk -F ";"  '{gsub($old_value,$new_value,$3)}1' OFS=";" >> file.txt  

when checking the file content ,I find the line unchanged

Can you help please?

CodePudding user response:

Assumptions:

  • want to change field #3 in all lines (assuming this code may be applied against a ;-delimited file that contains multiple lines)
  • do not know how many fields may exist in a line

Keeping with an awk solution whereby we simply replace field #3 ($3) with the new value:

$ laligne='a;b;c;d;e;f'
$ awk -v repl='new_value' 'BEGIN {FS=OFS=";"} {$3=repl; print}' <<< "${laligne}"
a;b;new_value;d;e;f

CodePudding user response:

Elements are separated by ";" so regexp "[^;]" will give them to us and we need 3rd :

$ echo "1;2;3;4;5;6" | sed "s/[^;]/replace/3"
1;2;replace;4;5;6
  • Related