我想將單詞分成單詞。我知道這可以做到這一點在bash中將一行分成單詞
For word in $line; do echo $word; done
但我想組3-3個字。所以我的問題是,我如何在3-3個字的組中劃分一條線?
例如
Input : I am writing this line for testing the code.
Output :
I am writing
this line for
testing the code.
我想將單詞分成單詞。我知道這可以做到這一點在bash中將一行分成單詞
For word in $line; do echo $word; done
但我想組3-3個字。所以我的問題是,我如何在3-3個字的組中劃分一條線?
例如
Input : I am writing this line for testing the code.
Output :
I am writing
this line for
testing the code.
作爲開始,你可以使用這個,讀取每一個字到一個數組
#!/bin/bash
total=0
while read
do
for word in $REPLY
do
A[$total]=$word
total=$(($total+1))
done
done < input.txt
for i in "${A[@]}"
do
echo $i
done
下一步是使用seq
或類似的函數循環訪問數組,並以三個一組的方式打印。
謝謝@Fredrik這解決了問題:) –
很高興我能幫上忙。歡迎來到SO,如果您喜歡答案,請不要忘記加註。 –
有一個非通用直接的解決方案:
#!/bin/bash
path_to_file=$1
while read line
do
counter=1;
for word in $line
do
echo -n $word" ";
if (($counter % 3 == 0))
then
echo "";
fi
let counter=counter+1;
done
done < ${path_to_file}
保存在一個腳本,給它一個名稱(test.sh例如),並將其設置爲執行模式。比,如果你的文本保存在「myfile.txt的」稱呼它:
test.sh myfile.txt
感謝您的幫助:) –
高興地幫助,閱讀常見問題http://stackoverflow.com/faq – hovanessyan
下面是一個可能的解決方案的例子。
#!/bin/bash
line="I am writing this line for testing the code."
i=0
for word in $line; do
((++i))
if [[ $i -eq 3 ]]; then
i=0
echo "$word"
else
echo -ne "$word "
fi
done
什麼粘貼命令
for word in $line; do echo $word; done | paste - - -
for word in $line; do echo $word; done | paste -d" " - - -
+1提醒我們粘貼如何工作。祝你們好運。 – shellter
易正則表達式的鍛鍊。
sed -e "s/\([^\ ]*\ [^\ ]*\ [^\ ]*\)\ /\1\\`echo -e '\n\r'`/g"
唯一棘手的部分就是在sed的新生產線,因爲沒有爲一個標準。
$ echo "I am writing this line for testing the code."|sed -e "s/\([^\ ]*\ [^\ ]*\ [^\ ]*\)\ /\1\\`echo -e '\n\r'`/g"
I am writing
this line for
testing the code.
不客氣。
一次只讀三個詞。將線從到其餘正在讀:
while read -r remainder
do
while [[ -n $remainder ]]
do
read -r a b c remainder <<< "$remainder"
echo "$a $b $c"
done
done < inputfile
正是我會建議,以及更好的寫作。 – Samveen
只需使用set
設置您輸入的位置參數,並在三組進行處理。這樣你就不需要任何花哨或bash特定的東西了:
line="I am writing this line for testing the code."
set junk $line
shift
while [ $# -ge 3 ]; do
echo "Three words: $1 $2 $3"
shift 3
done
它會每行總是9個字嗎?或者你的意思是儘可能均勻地將一個n-字線分成三組? – vergenzt
不可以有超過9個字。我只是想把整行分成3個字組。如果總字數不是3的倍數,最後一行可能少於三個字 –