
如何使用 sed 從清單中檢索隨機選擇的五個不同項目?我的清單如下。每個項目在一行的開頭都以星號開頭。
* asterisk*
star
wildcard
* bee
hive
* car
tire
drive
* dove
white
peace
* eel
slippery
* fin
fish
* goat
* hinge
door
* ice
cold
* jam
bread
我想要隨機五個不同的物品,如下:
* hinge
door
* ice
cold
* jam
bread
* asterisk*
star
wildcard
* eel
slippery
我怎樣才能做到這一點?
我使用的是 OSX,我無法在 sed 中使用分號,我必須使用 gshuf 而不是 shuf。我試過這個:
sed -e '1b' -e 's/^*/\x0*/' mypath | gshuf -zn 5 | tr -d '\000'
但它似乎只是添加了文字“x0”而不是空字符,它給了我這個:
* asterisk*
star
wildcard
x0* bee
hive
x0* car
tire
drive
x0* dove
white
peace
x0* eel
slippery
x0* fin
fish
x0* goat
x0* hinge
door
x0* ice
cold
x0* jam
bread
有什麼解決方法嗎?
答案1
和gnu sed/shuf
:
sed '1b;s/^*/\x0*/' infile | shuf -zn 5 | tr -d '\000'
這會將輸入轉換為 nul 分隔記錄,即在以 a 開頭的每一行*
(第一行除外)上,它會在*
then 使用shuf
with--zero-terminated
開關之前添加一個 nul 字符,以提取五個隨機記錄並tr
刪除這些nul 字符。
答案2
cat listfile | tr '\n' , | sed 's/,\*/\n*/g;s/,$//' | shuf | head -n 5 | tr , '\n'