1

I'm really new at Bash and scripting in general. I have to create usernames formed of first letter of first name followed by last name. To do it, I use a provided text file that looks like this:

doe,john
smith,mike
...

I declared the following variables:

fname=$(cut -d, -f2 "file.txt" | cut -c1)
lname=$(cut -d, -f1 "file.txt")

But how do I put the elements together to form the names jdoe and msmith ? I tried the methods I know to concatenate strings and vriables, but nothing works..

I think I found a method using awk that is supposed to work, but is there any other way to "concatenate" the elements of 2 lists? Thank you

sgh1980
  • 25
  • 4
  • Is this a roundabout way of asking how to [concatenate string variables in bash?](http://stackoverflow.com/questions/4181703/how-can-i-concatenate-string-variables-in-bash) – that other guy May 18 '15 at 21:51

3 Answers3

3

There's a million ways to do it, this is simplest:

$ awk -F, '{print substr($2,1,1) $1}' file
jdoe
msmith
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
1

This looks a bit too much like homework, so I'll just drop some hints.

To read the lastname and firstname into separate variables for each line of the file, see BashFAQ 1. It should not involve cut.

To grab the first character of a variable, see BashFAQ 100.

geirha
  • 5,801
  • 1
  • 30
  • 35
1

Ed Morton's awk-based answer is simplest (and probably fastest), but since you asked for a different solution:

#!/usr/bin/env bash

while IFS=, read -r last first _; do
  username=${first:0:1}${last}
  echo "username: $username"
done < file.txt
  • IFS=, read -r last first _ reads the first 2 ,-separated fields from each input line (_ is a dummy variable that receives the rest of the input line, if any; -r prevents interpretation of \ chars. in the input, which is usually what you want).
  • username=${first:0:1}${last} concatenates the 1st char. of variable $first's value with variable $last's value, simply by placing the two variable references next to each other.
  • < file.txt is an input redirection that sends file.txt's contents via stdin to the while loop.
Community
  • 1
  • 1
mklement0
  • 382,024
  • 64
  • 607
  • 775