linux - Bash 函数可以在不等待整个输入的情况下多次缩进流水线

我想要实现的目标:

  • 定义一个可用于管道输入的函数,例如echo input |我的函数
  • 此函数修改每一行输入,例如,它在开头添加缩进。
  • 这个函数可以重复使用两次,在这种情况下,它的修改(双缩进)两次,例如回显输入 |我的函数 | my_function 结果为 \t\tinput
  • 此函数不等待提供完整的输入,它可以直接打印出行而无需查看所有输入。

至于我的测试,请看下面的脚本:

#!/usr/bin/env bash

main() {
  echo 'first:'
  echo 'once' | tab_indent_to_right
  echo 'twice' | tab_indent_to_right | tab_indent_to_right
  {
    echo 'wait 2 sec'
    sleep 2
    echo 'wait 2 sec'
    sleep 2
    echo 'waited'
  } | tab_indent_to_right
}

tab_indent_to_right() {
  # while read -r line; do echo $'\t'"$line"; done  # ? double indent not working
  # awk -v prefix='\t' '{print prefix $0}'          # ? buffer not working
  # sed 's/^/\t/'                                   # ? buffer not working
  # xargs -I {} echo $'\t{}'                        # ? double indent not working
  # xargs -L1 echo $'\t'                            # ? double indent not working
}

main

tab_indent_to_right 中的每一行都是我解决问题的失败尝试。他们有两个不同的问题:

  • 双缩进不起作用,例如 tab_indent_to_right | tab_indent_to_right
  • 或者,这些行不会被直接刷新/打印,而是被缓冲。换句话说,该函数等待所有 sleep 并立即打印出所有内容,而不是在行出现时打印出来。

我怎样才能创建这个函数,以便两次调用都能给我想要的修改,而且脚本不会等待管道 shell 的完全执行?

最佳答案

我建议将 IFS 设置为空以保留空格/制表符。

tab_indent_to_right() {
  while IFS= read -r line; do echo $'\t'"$line"; done
}

https://stackoverflow.com/questions/74757248/

相关文章:

r - 你如何在 R 中打开连字符和逗号分隔的数字范围?例如 1,3,5-7 -> 1,3,5,6,

c# - Blazor (.net 7) 中的三种依赖注入(inject)语法有区别吗?

javascript - 使用 js 正则表达式验证 gsheet/excel 相对范围字符串

c++ - 从函数中获取两个数组并将它们存储在 C++ 中的不同数据类型数组中

r - 如何折叠 R 中分类变量的水平

rust - 类型 `&[u8]` 不能被 `usize` 索引?

c++ - 在 C++ 中有没有办法像在 Java 中那样进行垃圾回收?

python - 捕获具有正面前瞻性但不匹配模式的组的正则表达式

c# - 查找过去最近的日期

typescript - 从返回类型推断出窄字符串文字类型