bash - bash 嵌套读取并确认
问题描述
我正在尝试遍历 a 的每一行输出,grep
并根据交互式提示有条件地做一些事情。
我看过这些: 迭代 ls -l 输出的每一行
但我仍然无法实现我想要的。我认为关键区别在于这些示例中的大多数都是从文件中读取输入-我想使用命令。我尝试了以下许多变体:
#! /bin/bash
function test1()
{
local out=$(grep -n -a --color=always "target" file.txt)
while read -u 3 line; do
echo -e "$line"
read -r -p "ok? " response
echo "you said: $response"
if [[ "$response" == 'n' ]]; then
return
fi
done 3<&0 <<< $out
}
function test2()
{
grep -n -a --color=always "target" file.txt | while read line; do
echo -e "$line"
read -r -p "ok? " response
echo "you said: $response"
if [[ "$response" == 'n' ]]; then
return
fi
done
}
在test1()
FD 重定向中似乎没有做我想要的。test2()
似乎只是(不出所料)踩过我的第二个read
。我认为这是因为我需要切换正在使用的 FD。我试图将 FD 重定向从test1
into结合起来test2
,但我无法让它与管道一起使用。我正在使用 bash 4.4 版。我错过了什么?
以下是上述两个函数的运行示例:
[~]$ cat file.txt
ksdjfklj target alsdfjaksjf alskdfj asdf asddd
alsdfjlkasjfklasj
asdf
asdfasdfs
target
assjlsadlkfjakls target
target aldkfjalsjdf
[~]$
[~]$ test1
you said: 1:ksdjfklj target alsdfjaksjf alskdfj asdf asddd 6:target 7:assjlsadlkfjakls target 8:target aldkfjalsjdf
you said:
you said:
you said:
you said:
^C
[~]$
[~]$
[~]$ test2
1:ksdjfklj target alsdfjaksjf alskdfj asdf asddd
you said: 6:target
7:assjlsadlkfjakls target
you said: 8:target aldkfjalsjdf
[~]$
解决方案
done 3<&0 <<< $out
是相当折磨人的。替代流程怎么样?
test1() {
while IFS= read -r -u 3 line; do
printf '%s' "$line"
read -r -p "ok? " response
echo "you said: $response"
[[ "$response" == [nN]* ]] && return
done 3< <(
grep -n -a --color=always "target" file.txt
)
}
IFS= read -r
是完全逐字逐句的成语。
在 bash 中,您可以使用funcname()
orfunction funcname
但您不需要关键字和括号。
推荐阅读
- sql - 如何比较字符串变量和整数
- java - 这是在真实软件环境中制作构建器模式的正确方法吗?简而言之,在java中创建构建器模式的最佳方法是什么
- reactjs - Javascript 在使用 redux 时将类型从 int 隐式转换为 bool
- mongodb - Mongo:锁定单个文档以供 READ 和后续更新
- android - 为应用操作创建自定义内置 Intent
- python - 转换熊猫数据框中的嵌套字典
- html - angularJS脚本文件在html中调用时不起作用
- c# - INSERT 语句与 MVC 中的 FOREIGN KEY 约束冲突
- excel - 如何在 Z ie 之后将值粘贴到 VBA 中。AA、AB 等
- android - AndroidApplicationConfiguration 无法在 Android Studio 中解析