我想使用来自“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.
关键是“单词扩展”位。
lines=`wc file.txt | awk '{print $1}'`
words=`wc file.txt | awk '{print $2}'`
...
您还可以先将
wc
结果存储在某处..然后解析它..如果您对性能很挑剔:)
只是添加另一个变体--
set -- `wc file.txt`
chars=$1
words=$2
lines=$3
这显然会破坏
$*
和相关变量。与这里的一些其他解决方案不同,它可以移植到其他 Bourne shell。
我想将 csv 文件的数量存储在变量中。以下对我有用:
CSV_COUNT=$(ls ./pathToSubdirectory | grep ".csv" | wc -l | xargs)
您可以通过打开子 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"
另一种选择。
$ read lines words chars _ < <( wc file.txt )
$ printf 'lines: %s\nwords: %s\nchars: %s\n' $lines $words $chars
lines: 2
words: 5
chars: 23