簡體   English   中英

如何將文件的行隨機插入另一個文本文件?

[英]How do I insert lines of a file randomly into another text file?

我正在尋找一種將所有行從一個文件隨機插入另一個文件的方法。 詳細說明,假設我有 2 個文件:
toinsert.txt

insert1
insert2
insert3


mainfile.txt

line1
line2
line3
line4
line5
...

結果文件應如下所示,其中toinsert.txtmainfile.txt中的行隨機混合:

line1
insert1
line2
line3
insert2
...
insert3
...

有沒有辦法在 bash 中輕松做到這一點? 干杯!

您可以使用shuf命令和cat輕松完成此操作,例如

cat toinsert.txt mainfile.txt | shuf

這會將toinsert.txtmainfile.txt中的行以打亂的順序組合起來。 要將結果寫回mainfile.txt ,您需要使用中間臨時文件,例如

cat toinsert.txt mainfile.txt | shuf > tmp; mov -f tmp mainfile.txt

(當然要確保你還沒有tmp文件,否則它會被覆蓋)

如果您還有其他問題,請告訴我。

您基本上是在生成 3 個隨機數,在另一個文件的行數范圍內沒有重復。

喜歡:

mainfilecnt=$(wc -l <mainfile.txt)
toinsert=$(wc -l <toinsert.txt)
# copy input to output
cp mainfile.txt output.txt
# get as many random numbers as lines to insert in the range of lines
shuf -i 1-"$mainfilecnt" -n "$toinsertcnt" |
sort |
# join numbers with lines
paste - toinsert.txt |
# Reverse to insert from the last line
tac |
# we have number of line to insert to and a line.
# So insert it at that line number.
while IFS=$'\t' read -r num line; do
     sed -i -e "${num}i"<(printf "%s\n" "$line") output.txt
done

或喜歡:

# get as many random numbers as lines to insert in the range of lines
shuf -i 1-"$mainfilecnt" -n "$toinsertcnt" |
# sort reverse for inserting
sort -r |
# generate GNU sed script to insert numbers
sed 's/.*/&R'toinsert.txt'/' |
# Use xargs to pass generated sed script back to sed
xargs -0 -I{} sed {} mainfile.txt

在 repl 上測試

上面的腳本有一個錯誤/功能,該行不會作為第一行插入,僅作為第二行插入。 這些只是我為展示該方法而編寫的非常簡短的腳本——您應該根據您的實際需要對其進行改進。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM