linux,

Remove Last N Characters of a String in Bash

Sep 24, 2021 · 3 mins read · Post a comment
Remove Last N Characters of a String in Bash

As with most things in IT, there is always more then one way to skin a cat. In today’s blog post, we are gonna test out few ways on how we could remove last n characters of a string. I’ll use the same example from Convert Linux commands output from CSV to JSON post, so please check that out as well if you are interested.

Prerequisites

  • Access to Linux bash environment

Step 1. Let’s grep the disk free space info for the root block device and replace the spaces with commas:

df -h | grep -E 'Filesystem|/dev/sda2' | tr -s ' ' ',' 

Example output:

Filesystem,Size,Used,Avail,Use%,Mounted,on
/dev/sda2,40G,8.9G,29G,24%,/

If you could notice, we got this one annoying and unexpected thing with the output. There is a , (comma) between Mounted and on since they are meant to be shown as a single column named Mounted on. Let’s get rid of the ,on substring.

Expected output:

Filesystem,Size,Used,Avail,Use%,Mounted
/dev/sda2,40G,8.9G,29G,24%,/

Basically, you should get the same output with all of the commands described below.

cut command

df -h | grep -E 'Filesystem|/dev/sda2' | tr -s ' ' ','  | cut -d, -f7 --complement 

Note:

  • -d, parameter stands for delimiter, and in this case the delimiter is the comma.
  • -f7 parameter stands for fields, which means select only the 7th field from the beginning of the string.
  • --complement help us with the exclusion.

awk command

df -h | grep -E 'Filesystem|/dev/sda2' | tr -s ' ' ',' | awk '{if (NR==1) print substr($0, 1, length($0)-3); else print }' 

Note: In this one, we deal with conditionals. NR stands for Number of Records, so If we are on the first line, remove the last 3 characters, else print the rest.

sed command

df -h | grep -E 'Filesystem|/dev/sda2' | tr -s ' ' ',' | sed '1 s/.\{3\}$//'

Note: 1 s/.\{3\}$// removes the last 3 characters from the first line only. If you want to remove the last n characters from more then the first line, just remove the 1.

parameter expansion (one-liner example)

Step 1. And last but not least, probably the most easiest way to remove characters from one-liners is the following one:

temp_result=$(df -h | grep -E 'Filesystem' | tr -s ' ' ',')
echo $temp_result

Expected output:

Filesystem,Size,Used,Avail,Use%,Mounted,on

Step 2. Use the parameter extension and save the result as a new variable called updated_result:

updated_result=${temp_result::-3}
echo $updated_result

Expected output:

Filesystem,Size,Used,Avail,Use%,Mounted

Conclusion

In most of the cases, you might want to use these command line utilities together. In fact, there are a dozen other combos you could find easily on the internet.
Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on telegram.