1

If I have a bash string in a variable. How do I extract/retrieve that string except for the last character, and how easy would it be if I want to extract until the last two characters?

Example:

# Removing the last character
INPUT="This is my string."
# Expected output "This is my string"

# Removing the last two characters
INPUT="This is my stringoi"
# Expected output "This is my string"
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
RonPringadi
  • 1,294
  • 1
  • 19
  • 44

3 Answers3

7

With any POSIX shell:

OUTPUT="${INPUT%?}"  # remove last character
OUTPUT="${INPUT%??}" # remove last two characters
                     # and so on
oguz ismail
  • 1
  • 16
  • 47
  • 69
5

Sample:

INPUT="This is my string."
echo $INPUT |sed 's/.$//' # removes last character

INPUT="This is my stringoi"
echo $INPUT |sed 's/..$//' # removes last two character
Sreejith
  • 434
  • 3
  • 19
2

EDIT: Adding a generic solution here. You can mention number of characters which you want to remove from end of line in awk named remove_char and it should work accordingly then.

awk -v remove_char="2" '{print substr($0,1,length($0)-remove_char)}' Input_file


Could you please try following.

awk '{print substr($0,1,length($0)-1)}' Input_file


2nd solution: making field separator none with GNU awk

awk 'BEGIN{FS=OFS=""} {NF--} 1' Input_file
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93