a=$(find ./ -name "*-*.txt")
现在我需要从 $ a 中随机获得一行,但是 shuf 对我大喊
b=$(shuf -n1 $a)
shuf:额外的操作数
我的问题是什么? 谢谢!
答案 0 :(得分:1)
您可以为此使用$RANDOM。
注意:
public class ChooseLocationTask extends AsyncTask<String, Void, Void> {
OkHttpClient client = new OkHttpClient.Builder()
//default timeout for not annotated requests
.readTimeout(15000, TimeUnit.MILLISECONDS)
.connectTimeout(15000, TimeUnit.MILLISECONDS)
.writeTimeout(15000, TimeUnit.MILLISECONDS)
.build();
Request request;
private TextView location;
private TextView value;
String state;
Number probability;
String probablityString;
public ChooseLocationTask(TextView location, int selected, TextView value){
this.location = location;
this.value = value;
}
@Override
protected void onProgressUpdate(Void...values){
super.onProgressUpdate(values);
}
@Override
protected void onPreExecute(){
super.onPreExecute();
}
@Override
protected Void doInBackground(String... urls) {
request = new Request.Builder().url(urls[0]).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
Log.d("CallMsg", String.valueOf(call));
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.d("Response", String.valueOf(response));
try {
JSONObject jsonObject = new JSONObject(response.body().string());
JSONObject weather = jsonObject.getJSONObject("weather");
JSONObject location = weather.getJSONObject("location");
state = location.getString("state");
JSONObject percentage = jsonObject.getJSONObject("probability");
JSONObject calculated = percentage.getJSONObject("highest");
probability = calculated.getInt("value");
probablityString = probability.toString();
Log.d("percentage", probability.toString());
Log.d("String",probablityString);
Log.d("location",state);
} catch (JSONException e){
e.printStackTrace();
}
}
});
return null;
}
@Override
protected void onPostExecute(Void voids){
if(isCancelled()){
voids= null;
} else {
location.setText(state);
value.setText("your chance to see Northern lights today is" + probablityString);
Log.d("value", "onPostExecute: " + probablityString);
}
Log.d("post", "onPostExecute: " + probability);
}
}
给出数组的大小${#array[@]}
为您提供一个随机整数,而$((min + RANDOM % max))
不包含在内。max
那样访问索引为index_number
的数组项${array[index_number]}
答案 1 :(得分:1)
默认情况下,shuf
使用单个文件名参数,并随机播放该文件的内容。您希望它改组其参数。为此,请使用shuf -e
:
b=$(shuf -e -n1 $a)
顺便说一句,这有一个微妙的问题:它会被带有空格和/或通配符的文件名所混淆。也许在您的环境中不会发生,但是我更喜欢使用脚本惯用法,这些惯用法不会因有趣的文件名而失效。为了防止这种情况,请将文件名存储在数组中,而不要依靠分词来告诉一个停在哪里,下一个从哪里开始:
readarray -d '' -t arr < <(find ./ -name "*-*.txt" -print0)
b=$(shuf -en1 "${arr[@]}")
如果您不需要存储文件列表,那么事情就更简单了:
b=$(find ./ -name "*-*.txt" -print0 | shuf -zn1 | tr -d '\0')