Bash 作为变量的wc结果

Bash 作为变量的wc结果,bash,shell,wc,Bash,Shell,Wc,我想使用来自“wc”的行作为变量。例如: echo 'foo bar' > file.txt echo 'blah blah blah' >> file.txt wc file.txt 2 5 23 file.txt 我希望与值2、5和23关联一些类似$lines、$words和$characters。我怎么能在bash中做到这一点 lines=`wc file.txt | awk '{print $1}'` words=`wc file.txt | awk '{prin

我想使用来自“wc”的行作为变量。例如:

echo 'foo bar' > file.txt
echo 'blah blah blah' >> file.txt
wc file.txt

2  5 23 file.txt
我希望与值
2
5
23
关联一些类似
$lines
$words
$characters
。我怎么能在bash中做到这一点

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
在纯bash中:(无awk)

这通过使用bash的数组来实现
a=(1233)
创建一个包含元素1、2和3的数组。然后,我们可以使用
${a[indice]}
语法访问单独的元素

备选方案:(基于gonvaled解决方案)


还有其他解决方案,但我通常使用的一个简单方法是将
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
问题是管道到
read
会创建另一个进程,并且变量会在那里更新,因此在调用shell中无法访问它们

编辑:通过arnaud576875添加解决方案:

read lines words chars filename <<< $(wc x)
读取行字字符文件名
声明-结果
结果=($(wc
只需添加另一个变体--


这显然会破坏
$*
和相关变量。与这里的其他解决方案不同,它可以移植到其他Bourne Shell

我想将csv文件的编号存储在一个变量中。以下几点对我很有用:

CSV_COUNT=$(ls ./pathToSubdirectory | grep ".csv" | wc -l | xargs)
  • xargs从wc命令中删除空白
  • 我运行的这个bash脚本与csv文件不在同一个文件夹中。因此,pathToSubdirectory

您能解释一下为什么这样做吗?特别是,第一行周围的额外括号起什么作用?在bash中,外部的
(…)
创建一个数组,后面的行对该数组进行索引。否则结果只是一个三个数字的单个字符串在本例中,括号是$(command)命令替换语法的一部分;它相当于“command”,但括号表示法简化了嵌套。命令在子shell中运行,命令替换的文本被命令的输出替换,几乎就像您键入它一样。“几乎就像”是因为
a=x y z
x
分配给
a
,然后运行命令
y z
a=(x y z)
x
y
z
分配给数组
a
,但您不必像
a=($(echo x y z))那样键入额外的参数
因为分词发生得晚。比我的好,但你不需要file
xxx
或filename:
wc
@Adrian:请看我上面的评论:管道在另一个进程中创建变量,因此它们在调用shell中不可用。
read lines words chars@gonvaled:噢,是的,那个老陷阱@阿诺576875:我还没有看到

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
wc file.txt | read lines words characters filename
read lines words chars filename <<< $(wc x)
Here Strings

   A variant of here documents, the format is:

          <<<word

   The word is expanded and supplied to the command on its standard input.
declare -a result
result=( $(wc < file.txt) )
lines=${result[0]}
words=${result[1]}
characters=${result[2]}
echo "Lines: $lines, Words: $words, Characters: $characters"
set -- `wc file.txt`
chars=$1
words=$2
lines=$3
CSV_COUNT=$(ls ./pathToSubdirectory | grep ".csv" | wc -l | xargs)