Re: Access 1st 12 charectors of a word.
On 2006-08-22, Dave Kelly wrote:
> I have a list that is 3 words to each line.
> I know how to read the file.
> I need only the first 12 character of the 3 word. This word is not
> guaranteed to be 12 character long. This is where I'm stuck.
>
> Is there an equivalent to the old basic 'left$'? Where do I find it?
To get the first 12 characters of the third word of every line:
awk '{ printf "%s\n", substr($3,1,12) }'
If you only want lines where the thrid word contains at least 12
letters:
awk 'length($3) >=12 { printf "%s\n", substr($3,1,12) }'
If you want to process it in the shell:
word=qwertyuiopasdfghjklzxcvbnm
mask=????????????
junk=${word#$mask}
printf "%s\n" "${word%"$junk"}"
In bash or ksh93:
printf "%s\n" "${word:0:12}"
For other POSIX shells, there is a substr() function in my book
that can do it. (I may previously have posted it here. All the
scripts from the book are available on line.)
--
Chris F.A. Johnson, author <http://cfaj.freeshell.org>
Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
===== My code in this post, if any, assumes the POSIX locale
===== and is released under the GNU General Public Licence
|