循环遍历 bash 中的每一行文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9353882/
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
Loop over each line of text file in bash
提问by switz
Here's what the text looks like:
下面是文本的样子:
428, "http://www.youtube.com/watch?v=aqlJl1LfDP4", "NEW YORK,NEW YORK- FRANK SINATRA - YouTube", "moc.ebutuoy.www.", 1, 0, 0, 20, 96, 1329427038818198, "aiODk063S1YW"
429, "http://www.youtube.com/watch?v=KIiUqfxFttM&feature=list_related&playnext=1&list=AVGxdCwVVULXfJnKOaSACBmNaC6ZZ71zS7", "Frank Sinatra - That's Life - YouTube", "moc.ebutuoy.www.", 1, 0, 0, 20, 96, 1329427228164029, "96X5yyV88p8v"
id,url,title,...unnecessary info...
I want to grab each row of a text file in a bash script. Get the second parameter (url), and then patch that into a script.
我想在 bash 脚本中获取文本文件的每一行。获取第二个参数 (url),然后将其修补到脚本中。
I'm not really sure how to loop for each line, and then pull out that second param.
我不太确定如何循环每一行,然后拉出第二个参数。
Thanks
谢谢
采纳答案by Alex Howansky
for URL in $(cut -d, -f2 < file)
do
echo $URL
done
回答by Oliver Charlesworth
cut -f 2 -d " " thefile.txt
回答by ohaal
Print the second argument of each line:
打印每一行的第二个参数:
awk '{ print }' thefile.txt
To use it in a script (i.e. loop over it):
在脚本中使用它(即循环它):
for URL in `awk '{ print }' thefile.txt`
do
echo $URL
done
One important thing to note is that the "and ,will be included in the URL.
需要注意的一件重要事情是"和,将包含在 URL 中。
If you want to remove these, just grab the substring of the 2nd argument:
如果要删除这些,只需获取第二个参数的子字符串:
awk '{ print substr( , 2, length() -3 ) }' thefile.txt
We start at the 2nd character on the line, and show the full length -3 of the line.
我们从该行的第二个字符开始,并显示该行的全长 -3。
In a loop:
在一个循环中:
for URL in `awk '{ print substr( , 2, length() -3 ) }' thefile.txt`
do
echo $URL
done
回答by jon
Building on Oli's answer, you can remove beginning "and final ",using sed:
基于 Oli 的回答,您可以使用 sed删除开头"和",结尾:
cut -f 2 -d " " thefile.txt | sed -e "s/^\"//" -e "s/\"\,$//"

