Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I want to remove last character from a line:

[root@ozzesh ~]#df -h | awk  '{ print $5 }'
Use%
22%
1%
1%
59%
51%
63%
5%

Expected result:

Use
22
1
1
59
51
63
5
share|improve this question
1  
Is it always a % sign? –  Bernhard Jul 15 '13 at 5:55

4 Answers 4

sed 's/.$//'

To remove the last character. But you could also do:

df -h | awk 'NR > 1 {print $5+0}'

With the arithmetic expression ($5+0) we force awk to interpret the 5th field as a number, and anything after the number will be ignored.

share|improve this answer
    
I assume the $5+0 solution will work in this specific case? –  Bernhard Jul 15 '13 at 6:01
4  
{print +$5} will work as well... –  jasonwryan Jul 15 '13 at 6:37

With sed, this is pretty easy:

$ cat file
Use%
22%
1%
1%
59%
51%
63%
5%
$ sed 's/.$//' file
Use
22
1
1
59
51
63
5

The syntax is s(ubstitute)/search/replacestring/. The . indicates any character, and the $ the end of the line. So .$ will remove the last character only.

In this case, your complete command would look:

df -h | awk '{ print $5}' | sed 's/.$//'
share|improve this answer
1  
The pipe to sed is redundant: it can be done in awk: df -h | awk '{gsub(/%/,""); print $5}' –  jasonwryan Jul 15 '13 at 6:33
    
@jasonwryan Then I like Stephane's solution better. –  Bernhard Jul 15 '13 at 6:35

In awk, you could do one of

awk '{sub(/%$/,"",$5); print $5}'
awk '{print substr($5, 1, length($5)-1)}'
share|improve this answer

another approach:

mapfile -t list < <(df -h)
printf '%s\n' "${list[@]%?}"

Turn it into a function:

remove_last() {
  local char=${1:-?}; shift
  mapfile -t list < <("$@")
  printf '%s\n' "${list[@]%$char}"
}

Then call it like this:

remove_last '%' df -h

mapfile is a bash4 feature.

The catch here is that you must supply a character to remove; if you want it to just be whatever the last character happens to be then you must pass '?' or ''. quotes required.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.