Search code examples
bashsedgrepcuttr

How to keep only three letters in a variable in bash


I'm accepting user input, $1, asking for a date. People can't use the help page, so I'm forced to dumb it down when passing it through grep.

My input is Day-Mon-Year - where the day doesn't have a preceding 0 and the month is only 3 letters long.

I have everything done, except for the 3 letter 'cut-down.'

## stripping leading zero, turning words to lower-case & then capitalizing only the first letter ##
fdate=$(echo $1 | sed 's/^0//g' | tr '[:upper:]' '[:lower:]' | sed -e "s/\b\(.\)/\u\1/g")

Can anyone help me take "August," for example, and cut it down to Aug, in this single variable? Or perhaps another way? I'm open to anything.

Thanks in advance!


Solution

  • You can do this in bash, without external commands:

    a='0heLLo wOrld'
    a=${a#0}     # Remove leading 0. Change to ${a##0} to remove multiply zeros
    a="${a:0:3}" # Take 3 first characters
    a=${a,,}     # Lowercase
    a=${a^}      # Uppercase first
    printf "%s\n" "$a" # Hel
    

    Alternative it can be done in one sed command:

    % sed 's/^0//;s/\(.\)\(..\).*/\u\1\L\2/' <<< "0heLLo wOrld"
    Hel
    

    Breakdown

    s/^0//;                   # Remove leading 0. Change to 's/^0*//' to remove multiply zeros
    s/
      \(.\)\(..\)             # Capture first character in \1 and next two in \2
                 .*           # Match rest of string
                   /\u\1\L\2/ # Uppercase \1 and lowercase \2