我想使用来自“wc”的行作为变量。例如:
echo 'foo bar' > file.txt
echo 'blah blah blah' >> file.txt
wc file.txt
2 5 23 file.txt
我想有类似$lines
,$words
并$characters
与值2
,5
和相关联的东西23
。我怎么能在 bash 中做到这一点?
在纯 bash 中:(没有 awk)
a=($(wc file.txt))
lines=${a[0]}
words=${a[1]}
chars=${a[2]}
这通过使用 bash 的数组来工作。a=(1 2 3)
创建一个包含元素 1、2 和 3 的数组。然后我们可以使用${a[indice]}
语法访问单独的元素。
替代方案:(基于 gonvaled 解决方案)
read lines words chars <<< $(wc x)
或者在 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
为每个变量创建多个进程。缺点是您需要一个临时文件,之后应将其删除。
小心:这不起作用:
wc file.txt | read lines words characters filename
问题是管道read
创建另一个进程,并且变量在那里更新,因此在调用 shell 中无法访问它们。
编辑:由 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 shell。
我想将 csv 文件的数量存储在一个变量中。以下对我有用:
CSV_COUNT=$(ls ./pathToSubdirectory | grep ".csv" | wc -l | xargs)
lines=`wc file.txt | awk '{print $1}'`
words=`wc file.txt | awk '{print $2}'`
...
您也可以wc
先将结果存储在某处..然后解析它..如果您对性能很挑剔:)
您可以通过打开子 shell 将输出分配给变量:
$ 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"