簡體   English   中英

重擊排序STDIN

[英]Bash Sorting STDIN

我想編寫一個bash腳本,該腳本按不同文件中的規則對輸入進行排序。 第一條規則是將所有字符或字符串寫入file1。 第二條規則是將所有數字寫入file2。 第三個規則是將所有字母數字字符串寫入file3。 所有特殊字符必須忽略。 因為我不熟悉bash,所以我不知道該如何實現。

有人可以幫我嗎?

謝謝,Haniball

感謝您的回答,

我寫了這個腳本

#!/bin/bash

inp=0 echo "Which filename for strings?" 
read strg 
touch $strg
echo "Which filename for nums?"
read nums
touch $nums
echo "Which filename for alphanumerics?"
read alphanums
touch $alphanums
while [ "$inp" != "quit" ]
do
 echo "Input: "
 read inp
 echo $inp | grep -o '\<[a-zA-Z]+>' > $strg
 echo $inp | grep -o '\<[0-9]>' > $nums
 echo $inp | grep -o -E '\<[0-9]{2,}>' > $nums
done

在我運行它之后,它僅將字符串寫入stringfile中。

問候,Haniball

當然可以提供幫助。 看這里:

並且總是正確的將您的作業標記為“作業”;)

您可以嘗試如下操作:

<input_file strings -1 -a | tee chars_and_strings.txt |\
grep "^[A-Za-z0-9][A-Za-z0-9]*$" | tee alphanum.txt |\
grep "^[0-9][0-9]*$" > numonly.txt

上面的內容僅適用於美國-沒有國際字符(讀取unicode),這會使事情變得更加復雜。

grep就足夠了(您的問題有點含糊。如果我做錯了,請告訴我...)

使用以下輸入文件:

這是一個字符串,包含單詞,1和2中的一位數字以及整數42 1066

所有字符或字符串

$ grep -o '\<[a-zA-Z]\+\>' sorting_input
this
is
a
string
containing
words
single
digits
as
in
and
as
well

所有一位數字

$ grep -o '\<[0-9]\>' sorting_input
1
2

所有多位數

$ grep -o -E '\<[0-9]{2,}\>' sorting_input
42
1066

將輸出重定向到文件,即grep ... > file1

Bash確實不是執行此類任務的最佳語言。 在可能的情況下,ild強烈建議為此使用perl,python或tcl。

就是說,您可以使用shell重定向將輸入的所有stdin寫入一個臨時文件。 然后,使用grep之類的命令將匹配項輸出到另一個文件。 它可能看起來像這樣。

#!/bin/bash

cat > temp

grep pattern1 > file1
grep pattern2 > file2
grep pattern3 > file3

rm -f temp

然后像這樣運行它:

cat file_to_process | ./script.sh

我將保留與您匹配的模式的細節。

暫無
暫無

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

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