bash脚本在循环线路输入 [英] Bash Script Looping over line input

查看:90
本文介绍了bash脚本在循环线路输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做以下,基本工作原理。
该脚本尝试一些行插入到一个文件重写一遍。

但它剥离所有的空行和所有行填充。
主要的问题是,它不处理该文件的最后一行。
我不知道为什么。

 而读线;做
        < ...过程中的一些事情...>
        回声$ {}线和GT;> $ {} ACTION_PATH_IN。工作
     完成< $ {} ACTION_PATH_IN

可以做些什么来解决这个问题?


解决方案

 而IFS =读-r线;做
    ## 一些工作
    printf的'%s的\\ n'$行>>产量
完成< ≤(printf的'%S \\ n'$(猫输入))


  • 空IFS告诉不剥离开头和结尾的空格。

  • 从创建续行读-r prevents在EOL反斜杠。

  • 双引号的参数替换($行)以prevent从做分词和通配符其值的外壳。

  • 使用的printf'%s的\\ n'而不是回声,因为它处理值一样喜欢当可靠 -e -n

  • < ≤(printf的'%S \\ n'$(猫输入))是LF的丑陋的方式终止输入的内容。其他的结构是可能的,根据您的要求(管道,而不是从进程替换重定向如果可以,您的整个,而在子shell中运行)。结果
    它可能会更好,如果你只是确保它是处理之前LF-终止。

I'm doing the following, which basically works. The script tries to insert some lines into a file to rewrite it.

But it is stripping all blank lines and also all line padding. The main problem is that it does not process the last line of the file. I'm not sure why.

     while read line; do
        <... process some things ...>
        echo ${line}>> "${ACTION_PATH_IN}.work"
     done < "${ACTION_PATH_IN}"

What can be done to fix this?

解决方案

while IFS= read -r line; do
    ## some work
    printf '%s\n' "$line" >> output
done < <(printf '%s\n' "$(cat input)")

  • An empty IFS tells read not to strip leading and trailing whitespace.
  • read -r prevents backslash at EOL from creating a line continuation.
  • Double-quote your parameter substitution ("$line") to prevent the shell from doing word splitting and globbing on its value.
  • Use printf '%s\n' instead of echo because it is reliable when processing values like like -e, -n, etc.
  • < <(printf '%s\n' "$(cat input)") is an ugly way of LF terminating the contents of input. Other constructions are possible, depending on your requirements (pipe instead of redirect from process substitution if it is okay that your whole while runs in a subshell).
    It might be better if you just ensured that it was LF-terminated before processing it.

这篇关于bash脚本在循环线路输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆