Reputation: 47
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?
Upvotes: 0
Views: 513
Reputation: 188
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
Upvotes: 1
Reputation: 35006
Assumptions:
;
-delimited file that contains multiple lines)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
Upvotes: 3