Home > Back-end >  Bash pattern matching newline character in shell parameter expansion
Bash pattern matching newline character in shell parameter expansion

Time:02-25

I have a long variable in my bash script. I'm trying to iterate over it in chunks to do some processing. It's largely working:

    while [ ${#REMAINING_PLAN} -gt 0 ] ; do
      CURRENT_PLAN=${REMAINING_PLAN::65300} # Truncate to 65k and iterate

      # problematic line:
      CURRENT_PLAN=${CURRENT_PLAN%'\\n'*} # trim truncated string to the last newline
      
      PROCESSED_PLAN_LENGTH=$((PROCESSED_PLAN_LENGTH ${#CURRENT_PLAN})) # evaluate length of outbound batch and store
      
      # do some stuff not shown

      REMAINING_PLAN=${REMAINING_PLAN:PROCESSED_PLAN_LENGTH}
    done

I'm trying to truncate a variable to a max length, then further strip everything up to the last new line in the file, so that my next 'batch' starts its processing on a fresh line. But this statement isn't doing what I intend:

CURRENT_PLAN=${CURRENT_PLAN%'\\n'*} # does not actually trim truncated string to the last newline

What's wrong with it and how can I trim a string to the last instance of a newline?

CodePudding user response:

Converting my comment to answer so that solution is easy to find for future visitors.

You may use this in bash to strip off all characters after last line break:

CURRENT_PLAN="${CURRENT_PLAN%$'\n'*}"

$'\n' is C like construct that is used in bash to denote a line break.

  • Related