linux,

Remove last N characters of a string in Bash

Sep 24, 2021 · 3 mins read · Post a comment

As with most things in IT, there is always more than one way to skin a cat. In today’s blog post, we are going to 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

  • 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 ' ' ',' 

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 from all commands described below.

cut command

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

Note(s):

  • -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: Helps 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(s): 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(s): 1 s/.\{3\}$// removes the last 3 characters from the first line only. If you want to remove the last N characters from more than the first line, just remove the 1.

parameter expansion (one-liner example)

Step 1. And last but not least, probably the 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.