简体   繁体   English

在 bash while 循环中解析和回显字符串

[英]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:为什么在第一个:

  1. The lines are printed in a different order than the original file?这些行的打印顺序与原始文件不同?
  2. no operation is done on picture1_123.txt and picture1 is not printed? picture1_123.txt没有操作,没有打印picture1?

Thank you!谢谢!

What Was Wrong什么问题

Here's what your old code did:这是您的旧代码所做的:

  • On the first (and only) iteration of the loop, read line read the first line into line .在循环的第一次(也是唯一一次)迭代中, read line将第一行读入line
  • The 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变量。
  • Finally, your echo $line wrote the first line in entirety, with nothing being cut.最后,您的echo $line完整地写下了第一行,没有任何删减。
  • Because all input had been consumed by cut , nothing remained for the next read line to consume, so the loop never ran a second time.因为所有输入都被cut消耗掉了,所以下一个read line不会消耗任何输入,所以循环不会再运行第二次。

How To Do It Right如何做对

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM