「wc」からの行を変数として使用したいと思います。例えば:
echo 'foo bar' > file.txt
echo 'blah blah blah' >> file.txt
wc file.txt
2 5 23 file.txt
のようなものを持ち、値、$lines
、$words
および に$characters
関連付けたいと思います。どうすればbashでそれを行うことができますか?2
5
23
In pure bash: (no awk)
a=($(wc file.txt))
lines=${a[0]}
words=${a[1]}
chars=${a[2]}
This works by using bash's arrays. a=(1 2 3)
creates an array with elements 1, 2 and 3. We can then access separate elements with the ${a[indice]}
syntax.
Alternative: (based on gonvaled solution)
read lines words chars <<< $(wc x)
Or in sh:
a=$(wc file.txt)
lines=$(echo $a|cut -d' ' -f1)
words=$(echo $a|cut -d' ' -f2)
chars=$(echo $a|cut -d' ' -f3)
他の解決策がありますが、私が通常使用する簡単な解決策は、出力をwc
一時ファイルに入れて、そこから読み取ることです。
wc file.txt > xxx
read lines words characters filename < xxx
echo "lines=$lines words=$words characters=$characters filename=$filename"
lines=2 words=5 characters=23 filename=file.txt
awk
この方法の利点は、変数ごとに 1 つずつ、複数のプロセスを作成する必要がないことです。欠点は、後で削除する必要がある一時ファイルが必要なことです。
注意してください: これは機能しません:
wc file.txt | read lines words characters filename
問題は、へのパイプでread
別のプロセスが作成され、そこで変数が更新されるため、呼び出し元のシェルでアクセスできないことです。
編集:arnaud576875によるソリューションの追加:
read lines words chars filename <<< $(wc x)
ファイルに書き込まなくても動作します (パイプの問題もありません)。これはbash固有です。
bash マニュアルから:
Here Strings
A variant of here documents, the format is:
<<<word
The word is expanded and supplied to the command on its standard input.
重要なのは、「単語が展開された」ビットです。
別のバリアントを追加するだけです-
set -- `wc file.txt`
chars=$1
words=$2
lines=$3
これは明らかに$*
、関連する変数を破壊します。ここにある他のソリューションとは異なり、他の Bourne シェルに移植できます。
lines=`wc file.txt | awk '{print $1}'`
words=`wc file.txt | awk '{print $2}'`
...
結果を最初にどこかに保存してwc
から解析することもできます..パフォーマンスにうるさい場合:)
サブシェルを開くことで、出力を変数に割り当てることができます。
$ x=$(wc some-file)
$ echo $x
1 6 60 some-file
ここで、個別の変数を取得するための最も簡単なオプションは、次を使用することawk
です。
$ x=$(wc some-file | awk '{print $1}')
$ echo $x
1
declare -a result
result=( $(wc < file.txt) )
lines=${result[0]}
words=${result[1]}
characters=${result[2]}
echo "Lines: $lines, Words: $words, Characters: $characters"