![]() |
Hello and Welcome from United States to the UNIX and Linux Forums! Thank You for Visiting and Joining Our Global Community.
|
|
google unix.com
|
|||||||
| Forums | Register | Forum Rules | Links | Albums | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
| Shell Programming and Scripting Post questions about KSH, CSH, SH, BASH, PERL, PHP, SED, AWK and OTHER shell scripts and shell scripting languages here. |
More UNIX and Linux Forum Topics You Might Find Helpful
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| shell script parsing with sed | jjamd64 | UNIX for Dummies Questions & Answers | 5 | 12-11-2007 04:51 PM |
| Parsing a line in Shell Script | unishiva | Shell Programming and Scripting | 3 | 11-01-2007 04:30 PM |
| Help in parsing a CSV file with Shell script | mihirk | Shell Programming and Scripting | 10 | 06-24-2007 10:58 AM |
| Parsing a file in Shell Script | sendhilmani123 | Shell Programming and Scripting | 4 | 11-30-2006 02:29 AM |
| shell script argument parsing | rmjoe | Shell Programming and Scripting | 1 | 07-28-2005 03:37 PM |
![]() |
|
|
LinkBack | Thread Tools | Search this Thread |
Rating:
|
Display Modes |
|
|
|
||||
|
parsing a string in a shell script
I need to parse a string in a shell script. I understand there is some in built function to use that. can someone explain the syntax ?
Say, it is like this #!/bin/ksh read input # input is entered as 'welcome' #Now I want to extract say only first 4 characters or last four #characters. Thanks Asutosh |
|
|||||
|
Sure
substr( s, i, n ) Where: s is the string you want to perform the substr operation on i is the first character that you want to extract n is the last character you want to match So if you said substr( "hello", 2, 4 ) it would match the second, third and fourth character and return "ell". Let me explain the code I gave Code:
$ echo "welcome" | awk '{ print substr( $0, 0, 4 ) }'
Code:
$ echo "welcome" | awk '{ print substr( $0, length($0) - 3, length($0) ) }'
So here, I'm saying "return the substring from the first character (which is the length of the string minus 3), up until the very end of the string". To clarify this: Code:
$ echo "welcome" | awk '{ print (length($0) - 3), length($0) }'
4 7
|
|
|||||
|
Quote:
![]() I also missed a very simple solution too - you can use head and tail with the -c option e.g. (on Linux) echo "welcome" | head -c 4 echo "welcome" | tail -c 5 On HP-UX, you must use head -c -n 4 There's more than one way to do it with *nix! Cheers ZB |
![]() |
| Bookmarks |
| Tags |
| linux |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|