Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the first element of a string split with space

Tags:

bash

I am trying to get the name of the user after su in a bash script. I used the following code:

user=`who am i`
#user <- "user4035     pts/0        2017-04-02 05:13 (my-hostname)"
userarray=($user)
#userarray <- ["user4035", "pts/0", "2017-04-02 05:13", "(my-hostname)"]
user=${userarray[0]}
#outputs "user4035"
echo $user

It works correctly, but is it possible to achieve the same result with less number of commands?

like image 809
user4035 Avatar asked Apr 02 '17 10:04

user4035


People also ask

How do I split a string with first space?

Using the split() Method For example, if we put the limit as n (n >0), it means that the pattern will be applied at most n-1 times. Here, we'll be using space (” “) as a regular expression to split the String on the first occurrence of space.

How do you get the first part of a split in Python?

Use the str. split() method with maxsplit set to 1 to split a string and get the first element, e.g. my_str. split('_', 1)[0] . The split() method will only perform a single split when maxsplit is set to 1 .

How do you split a string with first space in Kotlin?

The whitespace characters consist of ' ' , '\t' , '\n' , '\r' , 'f' , etc. We can use the split() function to split a char sequence around matches of a regular expression. To split on whitespace characters, we can use the regex '\s' that denotes a whitespace character.

How do you split in space?

To split a string with space as delimiter in Java, call split() method on the string object, with space " " passed as argument to the split() method. The method returns a String Array with the splits as elements in the array. In the following program, we have taken a string and split it by space.


2 Answers

Another simple solution is cut with custom delimiter:

user=$(who am I | cut -d ' ' -f1)
echo $user
like image 148
Tomas Avatar answered Oct 05 '22 16:10

Tomas


Use bash parameter-expansion without needing to use arrays,

myUser=$(who am i)
printf "%s\n" "${myUser%% *}"
user4035

(or) just use a simple awk, command,

who am i | awk '{print $1}'
user4035

i.e. in a variable do,

myUser=$(who am i | awk '{print $1}')
printf "%s\n" "$myUser"

(or) if your script is run with sudo privileges, you can use this bash environment-variable,

printf "%s\n" "${SUDO_USER}"
like image 36
Inian Avatar answered Oct 05 '22 16:10

Inian