我有一个如下的测试文件。 (但是实际文件有1000余行和许多列)
@Version
我要按以下方式打印此文件。
apple,2
mango,5
coconut,10
我尝试将I have apple and the count is 2
I have mango and the count is 5
I have coconut and the count is 10
与while read line
一起使用,但没有获得实际输出。
有人可以帮我吗?
答案 0 :(得分:4)
您可以像这样使用awk
:
awk -F, '{print "I have", $1, "and the count is", $2}' file
I have apple and the count is 2
I have mango and the count is 5
I have coconut and the count is 10
尽管建议使用awk
,但是如果您正在寻找bash循环,请使用:
while IFS=, read -r f c; do
echo "I have $f and the count is $c"
done < file
答案 1 :(得分:1)
这里是sed中的一位。用相关的字符串替换每行的开头和逗号:
$ sed 's/^/I have /;s/,/ and the count is /' file
I have apple and the count is 2
I have mango and the count is 5
I have coconut and the count is 10
答案 2 :(得分:0)
如果文件很小,则可以使用read
来分隔行。
while IFS=, read fruit count; do
echo "I have $fruit and the count is $count"
done < file.txt
对于较大的文件,使用bash
进行迭代效率不高,而像awk
这样的文件读取整个文件会更合适。