Find the answer to your Linux question:
Results 1 to 3 of 3
Hi, guys. I want to write a bash script, which will read two strings: firstname and surname, then the script will generate a username. For example: the user name for ...
  1. #1
    Just Joined!
    Join Date
    Mar 2009
    Posts
    4

    How to truncate string in bash script?

    Hi, guys.

    I want to write a bash script, which will read two strings: firstname and surname, then the script will generate a username. For example: the user name for "Peter Brown" will be brownp.

    My questions are:
    1. how can I get first letter from variable $firstname?
    2. how can I join the two strings together?

    Thanks in advance

    -K

  2. #2
    Just Joined!
    Join Date
    Aug 2009
    Posts
    1
    Hi,
    for your first question answer is
    1) how can I get first letter from variable $firstname?

    str2=`echo $surname | cut -c1`

    for the second question answer is
    2. how can I join the two strings together?

    user=`echo $name$str2`

    finally i wrote a script for you to add a user automatically with user's surname
    example : username is sridhar and surname is gumpula
    it creates a user with "sridharg"

    see below the full code...

    #!/bin/bash
    echo "Please Enter your name.."
    read name
    echo "Enter your surname.."
    read surname
    str2=`echo $surname | cut -c1`
    user=`echo $name$str2`
    useradd $user
    echo password | passwd --stdin $user

  3. #3
    Just Joined!
    Join Date
    Sep 2009
    Location
    In another land where the breeze and the trees and flowers glow blue
    Posts
    1
    There is a better solution to the truncation question - better because it is simpler & built into the shell.

    I happened on it in my Linux In A Nutshell (4th Edition) on p.587 (Chapter 7 Bash - Pattern matching operators)

    ${variable:n:l}
    starting from n (where the first position is 0) returns a substring of length l.

    I just tried it out as I need just the first 2 numbers in a string.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...