[英]parse and echo string in a bash while loop
I have a file with this structure:我有一个具有这种结构的文件:
picture1_123.txt
picture2_456.txt
picture3_789.txt
picture4_012.txt
I wanted to get only the first segment of the file name, that is, picture1 to picture4.我只想获取文件名的第一段,即picture1到picture4。 I first used the following code:我首先使用了以下代码:
cat picture | while read -r line; do cut -f1 -d "_"; echo $line; done
This returns the following output:这将返回以下 output:
picture2
picture3
picture4
picture1_123.txt
This error got corrected when I changed the code to the following:当我将代码更改为以下内容时,此错误得到纠正:
cat picture | while read line; do s=$(echo $line | cut -f1 -d "_"); echo $s; done
picture1
picture2
picture3
picture4
Why in the first:为什么在第一个:
Thank you!谢谢!
Here's what your old code did:这是您的旧代码所做的:
read line
read the first line into line
.在循环的第一次(也是唯一一次)迭代中, read line
将第一行读入line
。cut
command read the entire rest of the file , and wrote the results of extracting only the desired field to stdout. cut
命令读取整个rest文件,将只提取所需字段的结果写入stdout。 It did not inspect, read, or modify the line
variable.它没有检查、读取或修改line
变量。echo $line
wrote the first line in entirety, with nothing being cut.最后,您的echo $line
完整地写下了第一行,没有任何删减。cut
, nothing remained for the next read line
to consume, so the loop never ran a second time.因为所有输入都被cut
消耗掉了,所以下一个read line
不会消耗任何输入,所以循环不会再运行第二次。The simple way to do this is to let read
separate out your prefix:做到这一点的简单方法是让read
分离出你的前缀:
while IFS=_ read -r prefix suffix; do
echo "$prefix"
done <picture
...or to just run nothing but cut
, and not use any while read
loop at all: ...或者只运行cut
,而不使用任何while read
循环:
cut -f1 -d_ <picture
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.