Saturday, December 22, 2007
Removing last two characters - BASH beginner
$ cat details.out
200KG
2567.89KG
132.3MG
1200MG
$ awk 'sub("..$", "")' details.out
200
2567.89
132.3
1200
Subscribe to:
Post Comments (Atom)
© Jadu Saikia www.UNIXCL.com
"Where there is a shell, there is a WAY !!" Blog on Awk, Sed, BASH ones liners and scripts.
© Jadu Saikia www.UNIXCL.com
4 comments:
I just used this as the last part of my own amateur BASH script!
Thanks so much!
I needed to take a list of numbers in a .txt file and:
(1)place them in ascending order (I used sort -n)
(2)append a three letter prefix to them (bxp, bca, etc.)
(3)place them in the following format: " number1, number2, number3, number4"
Here is what I cam up with:
sort -n 01.txt | awk '{print "bca"$1", "}' | tr -d "\n" | awk 'sub("..$", "")'
ubrayj, thanks a lot for reading my post :-)
The solution looks great. Here is one using sed:
$ cat 01.txt
4
5
3
1
8
2
$ sort -n 01.txt | sed 's/[0-9].*/bca&,/' | tr -d "\n" | sed 's/,$//'
bca1,bca2,bca3,bca4,bca5,bca8
//Jadu, India
Here is one rather slow way using bash, if you don't have awk/sed. "$(<file)" is the same as "$(cat file)". I used substring expansion combined with an arithmetic evaluation, subtracting 2 from the string length. Also don't forget the quotes around cat file or the newlines will not be processed as one might expect and read will just get one line as input.
$ cat file
123456
234567
345678
456789
567890
$ while read line; do [[ ${#line} > 2 ]] && echo ${line::$((${#line}-2))}; done <<< "$(<file)"
1234
2345
3456
4567
5678
I think the following is best for readability and conciseness.
rev details.out | --complement cut -b-2 | rev
Of course very inefficient, but if efficiency was an issue you would just use C over bash.
Post a Comment