Change the characters of each line between two patterns

I need to change certain characters between two patterns in each line.

Eample :: (file contents saved as myfile.txt file)

abc, def, 1, {,jsdfsd,kfgdsf,lgfgd}, 2, pqr, stu
abc, def, 1, {,jsdfsqwe,k,fdfsfl}, 2, pqr, stu
abc, def, 1, {,asdasdj,kgfdgdf,ldsfsdf}, 2, pqr, stu
abc, def, 1, {,jsds,kfdsf,fdsl}, 2, pqr, stu

I want to edit and save myfile.txt as below

abc, def, 1, {jsdfsd kfgdsf lgfgd}, 2, pqr, stu
abc, def, 1, {jsdfsqwe k fdfsfl}, 2, pqr, stu
abc, def, 1, {asdasdj kgfdgdf ldsfsdf}, 2, pqr, stu
abc, def, 1, {jsds kfdsf fdsl}, 2, pqr, stu

I used the following command to edit and save myfile.txt

sed '/1,/,/,2/{/1,/n;/,2/!{s/,/ /g}}' myfile.txt

This team did not help me achieve my goal. Please help solve this problem.

+4
source share
7 answers

awk would be more appropriate in this case:

awk 'BEGIN{ FS=OFS=", " }{ gsub(/,/, " ", $4); sub(/\{ /, "{", $4) }1' file

Output:

abc, def, 1, {jsdfsd kfgdsf lgfgd}, 2, pqr, stu
abc, def, 1, {jsdfsqwe k fdfsfl}, 2, pqr, stu
abc, def, 1, {asdasdj kgfdgdf ldsfsdf}, 2, pqr, stu
abc, def, 1, {jsds kfdsf fdsl}, 2, pqr, stu
+3
source

Since you also have a tag vim, you can do this in vim via:

:%normal 0f{vi{:s/\%V,/ /g^M

If the last two characters are actually Ctrl+ V, followed by Ctrl+M

+1

vim lookbehinds:

%s/\v(\{.*)@<=,(.*})@=/ /g 

, a { a } .

, a , afer a { , , :

%s/\v(\{)@<=,(.*})@=/ /g 
+1

- :substitute.

:%s/{\zs[^}]*\ze}/\=substitute(submatch(0)[1:], ',', ' ', 'g')

, , .

.:

:h sub-replace-expression
:h /\zs
:h submatch()
:h sublist
:h substitute()
+1

awk , .

awk 'match($0,/{.*}/){val=substr($0,RSTART,RLENGTH);gsub(/,/," ",val);gsub(/{ /,"{",val);gsub(/} /,"}",val);print substr($0,1,RSTART-1) val substr($0,RSTART+RLENGTH+1);next} 1'  Input_file

Liner.

awk '
match($0,/{.*}/){
  val=substr($0,RSTART,RLENGTH);
  gsub(/,/," ",val);
  gsub(/{ /,"{",val);
  gsub(/} /,"}",val);
  print substr($0,1,RSTART-1) val substr($0,RSTART+RLENGTH+1)
  next
}
1
'   Input_file
0

vim:

:%normal! 4f,xf,r f,r 

: ........... command mode
% ........... in the whole file
normal! ..... normal mode
4f, ......... jump inside { block
x ........... delete the first comma
f, .......... jump to the next comma
r<Space> .... replace comma with space
0

awk:

awk 'NR>1{gsub(/,/," ",$1); $0=RS $0}1' FS=} OFS=} RS={ ORS= file

awk '{gsub(/,/, " ", $2); $2="{" $2 "}"}1' FS='[{}]' OFS= file
0

Source: https://habr.com/ru/post/1695227/


All Articles