Wednesday, May 27, 2009

Some parameter substitution with bash



$ line="abcdefghij"

$ echo $line
abcdefghij

#Number of characters in the line
$ echo ${#line}
10

#No of characters - 4
$ echo $((${#line}-4))
6

#Removing last 4 characters (The value 6 below is obtained from above expression)
$ echo ${line::6}
abcdef

#Printing last 4 characters
$ echo ${line: -4}
ghij


With this reference lets try to remove last 4 charactes from all lines of the following input file:

$ cat details.txt
some junk chrs
some more junks
pull some more chrs
this is just an example

The bash script(On prompt):

$ while read line
do
echo ${line::$((${#line}-4))}
done < details.txt

Output:
some junk
some more j
pull some more
this is just an exa


Related post:
- Bash script to find its own location
- Remove last two characters using awk
- Print last two characters using awk and sed
- Bash parameter substitution is well explained here and here

6 comments:

Nathan said...

nice one!!!

Unknown said...

@Nathan,inspired by you :-)

Mahesh Kharvi said...

May be this will be more efficient.

awk '{l=length($0);print substr($0,1,l-4)}'

Unknown said...

@Mahesh, thanks for your comment. I was trying some pure bash parameter substitutions; appreciate your awk one. Keep in touch.

Nandinho said...

Hi, sorry for this trouble, I´m trying to create a new post, I´ve got a file with the following contents:
HGSUI:IMSI=643012107864089,MSISDN=258820000011;
HGSDC:MSISDN=258820000011,SUD=CAT-10&DBSG-1&OBOPRE-1&OBOPRI-1&BS3G-1&TS11-1&TS21-1&TS22-1&RSA-1&CSP-11&NAM-0&TSMO-0&SCHAR-4&REDMCH-1
and I want to extract all IMSI and MSISDN numbers with the CSP-50 to another file. Pls can you guys help?

Unknown said...

@Retagi,

something like this:
$ cat file.txt
HGSUI:IMSI=643012107864071,MSISDN=258820000016;
HGSDC:MSISDN=258820000011,SUD=CAT-10&DBSG-1&OBOPRE-1&OBOPRI-1&BS3G-1&TS11-1&TS21-1&TS22-1&RSA-1&CSP-50&NAM-0&TSMO-0&SCHAR-4&REDMCH-1
HGSUI:IMSI=643012107864089,MSISDN=258820000011;
HGSDC:MSISDN=258820000011,SUD=CAT-10&DBSG-1&OBOPRE-1&OBOPRI-1&BS3G-1&TS11-1&TS21-1&TS22-1&RSA-1&CSP-11&NAM-0&TSMO-0&SCHAR-4&REDMCH-1
HGSUI:IMSI=643012107864070,MSISDN=258820000012;
HGSDC:MSISDN=258820000011,SUD=CAT-10&DBSG-1&OBOPRE-1&OBOPRI-1&BS3G-1&TS11-1&TS21-1&TS22-1&RSA-1&CSP-50&NAM-0&TSMO-0&SCHAR-4&REDMCH-1

$ awk '/&CSP-50&/{print x};{x=$0}' file.txt | sed 's/.*IMSI=\(.*\),MSISDN=\(.*\);/\1 \2/g'

643012107864071 258820000016
643012107864070 258820000012


Please let me know if your expected output is different. Thanks for posting.

© Jadu Saikia www.UNIXCL.com