Search code examples
sedtcsh

Extracting a value from a string using sed


I have the following code:

set MARKER_LIST = "t14_noTap_leftSlow t24_noTap_leftMedium t34_noTap_leftFast \
 t44_noTap_rightSlow t54_noTap_rightMedium t64_noTap_rightFast \
 t74_noTap_inphaseSlow t84_noTap_inphaseMedium t94_noTap_inphaseFast \
 t104_noTap_antiphaseSlow t114_noTap_antiphaseMedium t124_noTap_antiphaseFast"

foreach code (${MARKER_LIST})

set evt_code = `echo ${code} | sed 's/^.*t[0-9]*_noTap_//'`
echo "Extracted value: $evt_code"
end

I'm trying to extract the string after "tXX_noTap_" and "tXXX_noTap_" but it doesn't seem to be working. Would appreciate any help with this. Thanks!


Solution

  • Your problem is that you do not declare tcsh as the shell to interpret the script. So sh-aware code is expected. Start your script with the correct shebang in the first line:

    #!/usr/bin/tcsh
    

    Just beyond your question:

    1. Your sed code itself is fine, but perhaps unnecessary complicated:

      sed 's/^.*_//' 
      

      should be enough, except you expect output with _ in the desired part of the string.

    2. Please eliminate all the \ with their line breaks in ${MARKER_LIST}. Else the result will contain empty values at each appearance of \:

      Extracted value: leftSlow
      Extracted value: leftMedium
      Extracted value: leftFast
      Extracted value: 
      Extracted value: rightSlow
      Extracted value: rightMedium
      Extracted value: rightFast
      Extracted value: 
      Extracted value: inphaseSlow
      Extracted value: inphaseMedium
      Extracted value: inphaseFast
      Extracted value: 
      Extracted value: antiphaseSlow
      Extracted value: antiphaseMedium
      Extracted value: antiphaseFast
      

    So this would be your script:

    #!/usr/bin/tcsh
    
    set MARKER_LIST = "t14_noTap_leftSlow t24_noTap_leftMedium t34_noTap_leftFast t44_noTap_rightSlow   t54_noTap_rightMedium t64_noTap_rightFast t74_noTap_inphaseSlow t84_noTap_inphaseMedium t94_noTap_inphaseFast t104_noTap_antiphaseSlow t114_noTap_antiphaseMedium t124_noTap_antiphaseFast"
    
    foreach code (${MARKER_LIST})
        set evt_code = `echo ${code} | sed 's/^.*t[0-9]*_noTap_//'`
        echo "Extracted value: $evt_code"
    end