我想使用来自'wc'的行作为变量。例如:wc的结果作为变量
echo 'foo bar' > file.txt
echo 'blah blah blah' >> file.txt
wc file.txt
2 5 23 file.txt
我想有类似关联的值2
,5
$lines
,$words
和$characters
和23
。我怎么能在bash中做到这一点?
我想使用来自'wc'的行作为变量。例如:wc的结果作为变量
echo 'foo bar' > file.txt
echo 'blah blah blah' >> file.txt
wc file.txt
2 5 23 file.txt
我想有类似关联的值2
,5
$lines
,$words
和$characters
和23
。我怎么能在bash中做到这一点?
还有其他的解决方案,但一个简单的,我平时用的是放的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.
的关键是 “字展开” 位。
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)
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)
你能解释为什么这个工作?特别是,第一行附加的括号是做什么的?没有它们,它不再起作用,所以它们显得非常重要。 –
在bash中,外部'(...)'创建一个数组,其后面的行索引。否则结果只是一个由三个数字组成的单个字符串 –
在这种情况下,括号是$(_ command_)命令替换语法的一部分;它等同于\ command,但括号表示法简化了嵌套。 _command_运行在一个子shell中,并且命令替换的文本被_command_的输出替换,就好像您输入了它一样。 –
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
这显然则会覆盖$*
和相关变量。与其他一些解决方案不同,它可以移植到其他Bourne shell。
比我好,但你不需要文件'xxx'或文件名:'wc
@Adrian:请参阅我上面的评论:管道在另一个进程中创建变量,所以它们在调用shell中不可用。 – dangonfast
''读行字字符<<< $(wc x)'没有写入文件(并且没有管道问题)的作品 – arnaud576875