Ruba
Ruba

Reputation: 837

How can I split input using bash?

I have to write a script in Linux, that takes input from user.

For example, this could be a line of input:

name = Ruba

I need to take the "Ruba" from the input, so how can i split the input and take the last part?

Upvotes: 4

Views: 5814

Answers (4)

jaypal singh
jaypal singh

Reputation: 77095

#!/bin/bash
read input
awk -F"= " '{print $2}' <<<"$input"

Upvotes: 0

wkl
wkl

Reputation: 79901

You can use IFS in bash, which is the "internal field separator" and tells bash how to delimit words. You can read your input in with IFS set to a space (or whatever delimiter) and get an array back as input.

#!/usr/bin/env bash

echo "Type in something: "

# read in input, using spaces as your delimiter.
# line will be an array
IFS=' ' read -ra line

# If your bash supports it, you can use negative indexing
# to get the last item
echo "last item is: ${line[-1]}"

Test run:

$ ./inscript.sh 
Type in something: 
name = ruba
last item is: ruba

Upvotes: 4

Deept Raghav
Deept Raghav

Reputation: 1460

#!/bin/bash
read input
echo $input |cut -d'=' -f2 | read name

Upvotes: 3

Alessandro Pezzato
Alessandro Pezzato

Reputation: 8802

If you want to read name:

#!/bin/bash
read -p "Name: " name
echo $name

The code above prompts for name and output it.

If your input is "name = Ruba"

#!/bin/bash
read name
name=$( echo $name | sed 's/.*=\ *//' )
echo $name

The code above read a line like "name = Ruba" and remove all characters preceding = and spaces after =.

Upvotes: 2

Related Questions