2016-06-27 5 views
1

私は今ここで非常に多くの記事を読んでおり、私の頭は爆発的です。 "正しい"解決策を見つけることができないかもしれません、おそらく私の悪い英語が理由であり、確かに私の本当に低い技術のbashのものです。Bash:Variable1>最初にn個の単語を取得> cut> Variable2

私は、ユーザー(私)の入力を変数に読み込むスクリプトを作成しています。私が欲しいもの

read TEXT 
echo $TEXT 
Hello, this is a sentence with a few words. 

は(私は確信している)かもしれない非常に簡単です:私は2番目の変数になりました最初のn個の単語が必要です。

$TEXT tr/csplit/grep/truncate/cut/awk/sed/whatever get the first 5 words > $TEXT2 
echo $TEXT2 
Hello, this is a sentence 

のように私は、たとえば${TEXT:0:10}のために使用しましたが、これは単語の途中にもカットします。そして、私はtxt-file-input〜outputs、変数だけを使いたくありません。大きな、複雑なコードブロックや何百もの(/ [{* + $ ' - :% "})] ...などで本当に低レベルでシンプルなソリューションがありますか:(

cutを使用して

任意のサポートのおかげでたくさん!

+1

'text2 = $(cut -d '' -f1-5 <<<" $ text ")'は仕事をします – anubhava

+1

ああ、そうです。本当にありがとう!私は盲目だった...完璧に働く! :D – user3454869

答えて

0

は簡単な解決策かもしれないが、以下のソリューションはxargs

-n max-args 
      Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s 
      option) is exceeded, unless the -x option is given, in which case xargs will exit. 
manページから xargs

firstFiveWords=$(xargs -n 5 <<< "Hello, this is a sentence with a few words." | awk 'NR>1{exit};1') 

$ echo $firstFiveWords 
Hello, this is a sentence 

とあまりにも動作します210

awk 'NR>1{exit};1'は、その入力から最初の行を出力します。

+0

ありがとう! :) – user3454869

関連する問題