0

I have file like this in variable (let's say ${var_file}):

ABC+123+456+789+12'\r
DEF+987+98790+12+00'\r
GHI+12+12?+39+123498345+21+1'\r
ABC+485+2?'\r
ABC+34?+8kj+3949+1+sdfkj+sdfkj'\r
GHC+++sdf'\r
ABC+123++235+5435'\r

I also have a variable $var1 containing number in INT format and $var2 containing start of line.

I need a sed command (or awk/cut?) or function that will be part of bash script, that will replace $var1 position between + delimiters on $var2 line start (for example ABC or ABC+123), globally on the file (for all possible lines). There is also possibility of ?+, since ? is escape character, so in this case + does not work as delimiter, it's normal text. Lines should be always long enough to contain defined + count in $var1 for selected line start in $var2.

Example of output for position 3 ($var1 = "3", between 3rd and 4th +) on line starting with ABC+123 ($var2 = "ABC+123")

Therefore output should be:

ABC+123+456++12'\r
DEF+987+98790+12+00'\r
GHI+12+12?+39+123498345+21+1'\r
ABC+485+2?'\r
ABC+34?+8kj+3949+1+sdfkj+sdfkj'\r
GHC+++sdf'\r
ABC+123+++5435'\r

The change is on line 1 and line 7.

In case of just delete 3rd position ($var1 = "3") on line starting with ABC ($var2 = "ABC"):

ABC+123+456++12'\r
DEF+987+98790+12+00'\r
GHI+12+12?+39+123498345+21+1'\r
ABC+485+2?'\r
ABC+34?+8kj+3949++sdfkj+sdfkj'\r
GHC+++sdf'\r
ABC+123+++5435'\r

The change is on line 1, 5 and 7.

Can someone help me with this? I tried various sed commands and i just can't find solution..

Thank you!

Kalamarico
  • 5,466
  • 22
  • 53
  • 70
Kaleb
  • 55
  • 3

2 Answers2

2

Your question isn't very clear but I THINK what you want to do is:

awk -v start="$var2" -v col="$var1" '
    BEGIN { FS=OFS="+" }
    { gsub(/[?][+]/,RS) }
    index($0,start)==1 { $(col+1)="" }
    { gsub(RS,"?+") } 1
' file
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0

You can try this one with sed

sed 's/?+/\n/g;/'"$var2"'/s/\(+[^+]*\)/+/'"$var1"';s/\n/?+/g' file
ctac_
  • 2,413
  • 2
  • 7
  • 17
  • Just be aware that's treating `var2` as a regexp instead of a string and so may produce undesirable results if var2 contains any BRE metacharacters, It's also testing for var2 anywhere on the line instead of at the start of the line but an anchor would fix that, – Ed Morton Oct 25 '17 at 23:29