在循环迭代1次的同时进行bash

在循环迭代1次的同时进行bash,bash,sed,while-loop,Bash,Sed,While Loop,通过在/etc/drush中运行此命令,我获得一个文件input.txt或url/ ls /etc/drush | grep test | sed s/.alias.drushrc.php//g | sed '/^$/d' > input.txt 我将其输入如下循环: while read a; do echo "url: $a" done < input.txt cat input.txt | while read a; do echo "url: $a" d

通过在/etc/drush中运行此命令,我获得一个文件input.txt或url/

ls /etc/drush | grep test  | sed s/.alias.drushrc.php//g | sed '/^$/d' > input.txt
我将其输入如下循环:

while read a; do
    echo "url: $a"
done < input.txt
cat input.txt | while read a; do
    echo "url: $a"
done
www.first.com
www.something.com
www.something.com
www.last.com
我总是得到一个额外的网址:在最后,并已验证没有空行。我跟你确认了

cat input.txt
知道是什么导致了额外的迭代吗

input.txt如下所示:

while read a; do
    echo "url: $a"
done < input.txt
cat input.txt | while read a; do
    echo "url: $a"
done
www.first.com
www.something.com
www.something.com
www.last.com
输出如下所示

url: www.first.com
url: www.something.com
url: www.something.com
url: www.last.com
url: 

额外的迭代可能是因为输入文件末尾有一个空行。您可以使用tail-n3input.txt | od-ax之类的工具进行检查

我建议检查循环中的空行:

while read a; do
    if [[ -z "$a" ]]; then continue; fi
    echo "url: $a"
done < input.txt

如果以下字符串的长度为零,-z检查将返回true。如果是,我们让while循环跳过该迭代。

我们可以做得比

ls /etc/drush | grep test  | sed s/.alias.drushrc.php//g | sed '/^$/d' > input.txt
以下内容纯粹是在处理过程中—在任何地方都没有外部命令—因此速度更快,更不容易出现错误:

files=( /etc/drush/*test* )  # glob-expand to generate a list of full paths
files=( "${files[@]##*/}" )  # remove everything up to and including the last '/'
files=( "${files[@]//.alias.drushrc.php/}" ) # remove .alias.drushrc.php from names
for url in "${files[@]}"; do # iterate over names in the array
  echo "url: $url"
done
如果.alias.drushc.php是一个扩展名,而不是文件名中任何地方都可以找到的扩展名,则可以将该行改为:

files=( "${files[@]%.alias.drushrc.php}" )
要理解此处的表达式,请参阅或


要理解为什么原始版本存在错误,您可以从开始,并另外注意,换行符是POSIX系统上文件名中的有效字符。

您可以在问题中添加您得到的结果和您期望的结果吗?dos行结束?cat-vET input.txt您需要提供一个字节对一个字节的输入示例,以使问题变得可行。结尾带有隐藏字符的行比行为与指定行为相反的假定读取更有可能…因此,在使用GNU cat的系统上,您可以使用cat-A input.txt,或其他od-ax,这是我们没有要求您运行cat input.txt的原因,但是,根据您的cat或od-ax版本,您可以使用cat-A input.txt或cat-vET input.txt来代替cat-A input.txt或cat-vET input.txt,hiss re:不必要地使用cat。我一定是无知的。哪种做法被称为最佳实践?我一直认为命令读取总是更干净、更灵活。创建管道意味着有一个隐式的子shell。它有很高的性能成本,也意味着您的代码不会对父进程产生副作用-尝试设置或更新循环中的变量,当循环退出时,您会看到它消失了…请参阅,同时请注意,您可以在读取时写入