我想要实现的目标:
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/