Linux 在bash脚本循环中打印cat语句的输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6868377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print output of cat statement in bash script loop
提问by geoffrobinson
I'm trying to execute a command for each line coming from a cat command. I'm basing this on sample code I got from a vendor.
我正在尝试为来自 cat 命令的每一行执行一个命令。我基于从供应商那里获得的示例代码。
Here's the script:
这是脚本:
for tbl in 'cat /tmp/tables'
do
echo $tbl
done
So I was expecting the output to be each line in the file. Instead I'm getting this:
所以我期望输出是文件中的每一行。相反,我得到了这个:
cat
/tmp/tables
That's obviously not what I wanted.
这显然不是我想要的。
I'm going to replace the echo with an actual command that interfaces with a database.
我将用一个与数据库接口的实际命令替换 echo。
Any help in straightening this out would be greatly appreciated.
任何帮助解决这个问题将不胜感激。
采纳答案by Soren
You are using the wrong type of quotes.
您使用了错误类型的引号。
You need to use the back-quotes rather than the single quote to make the argument being a program running and piping out the content to the forloop.
您需要使用反引号而不是单引号来使参数成为正在运行的程序并将内容输出到 forloop。
for tbl in `cat /tmp/tables`
do
echo "$tbl"
done
Also for better readability (if you are using bash), you can write it as
同样为了更好的可读性(如果你使用 bash),你可以把它写成
for tbl in $(cat /tmp/tables)
do
echo "$tbl"
done
If your expectations are to get each line (The for-loops above will give you each word), then you may be better off using xargs
, like this
如果你期望得到每一行(上面的 for 循环会给你每个词),那么你最好使用xargs
,像这样
cat /tmp/tables | xargs -L1 echo
or as a loop
或者作为一个循环
cat /tmp/tables | while read line; do echo "$line"; done
回答by Daniel Gallagher
The single quotes should be backticks:
单引号应该是反引号:
for tbl in `cat /etc/tables`
Although, this will not get you output/input by line, but by word. To process line by line, you should try something like:
虽然,这不会让您按行输出/输入,而是按字。要逐行处理,您应该尝试以下操作:
cat /etc/tables | while read line
echo $line
done
回答by Prince John Wesley
With whileloop:
使用while循环:
while read line
do
echo "$line"
done < "file"
回答by bertramlau
You can do a lot of parsing in bash by redefining the IFS (Input Field Seperator), for example
例如,您可以通过重新定义 IFS(输入字段分隔符)在 bash 中进行大量解析
IFS="\t\n" # You must use double quotes for escape sequences.
for tbl in `cat /tmp/tables`
do
echo "$tbl"
done