我必須在Linux中編寫一個腳本,它接受來自用戶的輸入。如何使用bash分割輸入?
例如,這可能是輸入的一行:
name = Ruba
我需要從輸入"Ruba"
,所以,我怎麼可以拆分輸入,並採取最後一部分?
我必須在Linux中編寫一個腳本,它接受來自用戶的輸入。如何使用bash分割輸入?
例如,這可能是輸入的一行:
name = Ruba
我需要從輸入"Ruba"
,所以,我怎麼可以拆分輸入,並採取最後一部分?
您可以使用IFS
in bash,這是「內部字段分隔符」,並告訴bash如何分隔單詞。你可以用IFS
設置一個空格(或任何分隔符)來讀取你的輸入,並將數組作爲輸入。
#!/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]}"
試運行:
$ ./inscript.sh
Type in something:
name = ruba
last item is: ruba
如果你想讀的名字:
#!/bin/bash
read -p "Name: " name
echo $name
上面的代碼提示輸入姓名和輸出。
如果輸入是「名稱=魯巴」
#!/bin/bash
read name
name=$(echo $name | sed 's/.*=\ *//')
echo $name
上述讀出的代碼,如「名稱=魯巴」的線和後=除去前述=和空格的所有字符。
#!/bin/bash
read input
echo $input |cut -d'=' -f2 | read name
#!/bin/bash
read input
awk -F"= " '{print $2}' <<<"$input"
哪個Shell? bash,sh,csh,zsh,qzs,ksh,hash? – 2011-12-28 20:58:01
Ruby,Python,Lua,CoffeeScript? – 2011-12-28 20:59:22
如果你把'Ruba'作爲輸入,你在分裂什麼?什麼是'最後一部分'? – birryree 2011-12-28 20:59:42