【问题标题】:Substring Detection not able to detect newline子字符串检测无法检测到换行符
【发布时间】:2021-07-23 09:45:26
【问题描述】:

我的代码检查了一个文本文件并对其进行了一些处理。我最终无法处理(缺少)换行符。我想测试该行是否在行尾有换行符。如果是这样,我想在文件的行中添加一个换行符。现在,我的代码根本没有添加任何新行,我不太清楚为什么。

用 Google 搜索过,但没有任何效果。

while read line || [ -n "$line" ]; do
 ...#Do things
        SUB="\n"
        if [[ "$line" =~ .*"$SUB".* ]]; then
            echo "It's there."
            printf "\n" >> $DEC
        fi
done <ip.txt

我只能使用 bash(没有 sed、awk 等)。

我想要:

案例一:

ip:

Line1 (\n here)
Line2 (\n here)
Line3(no \n here)

输出:

line1 (\n here)
line2 (\n here)
line3 (no \n here)

案例 2:

ip:

Line1 (\n here)
Line2(\n here)
Line3(\n here)

输出:

line1 (\n here)
line2 (\n here)
line3 (\n here)

但我明白了:

line1(no space)line2(no space)line3

两种情况

【问题讨论】:

  • 不确定我是否理解目标,也不知道您希望如何匹配一行中间的“换行符”字符 ("$line" =~ .*"$SUB".*),所以 fwiw ...SUB="\n" 会继续将 2 个字符的字符串分配给 SUB ... 字符 '\' 和 'n';分配换行符尝试SUB=$'\n'
  • 我不希望。在所有用于换行的谷歌解决方案都不起作用之后,我只是检查了子字符串检测。认为它应该工作
  • @markp-fuso 你给我的 sub 不起作用。它没有被检测到

标签: bash shell file io scripting


【解决方案1】:

您当前的方法存在两个问题。第一个是read 从行尾删除换行符,因此您无法检查换行符的结果——它不会存在。如果read 到达文件结尾而不是换行符,它将返回错误状态,这就是为什么您需要|| [ -n "$line" ] 来防止循环在读取未终止的行时退出。

第二个问题是SUB="\n"在变量中存储了一个反斜杠和一个“n”;要获得换行符,请使用SUB=$'\n'

根据您在循环中尝试执行的其他操作,有多种选择。如果在文件末尾添加缺少的换行符是唯一的目标,那么this question 的答案中有很多选项。

如果您需要通读这些行,在 shell 中处理它们,然后在最后添加缺少的换行符输出它们,然后只需使用当前循环,并在每一行输出一个换行符 - 您需要添加它,无论它最初是否存在,如果您始终添加它,它就会一直存在。

如果您需要明确找出最后一行是否有换行符并在有换行符时做一些不同的事情,一个选择是稍微修改您的原始代码:

while read line; do
    # process lines that had newlines at the end
done <ip.txt
if [ -n "$line" ]; then
    # final line was missing a newline; process it here
fi

另一个选择是将整个文件读入一个数组(每行作为一个数组条目),因为mapfile 不会删除行终止符(除非您特别要求它使用-t):

mapfile ipArray <ip.txt
for line in "${foo[@]}"; do
    if [[ "$line" = *$'\n' ]]; then
        # Process line with newline at end
        cleanLine="${line%$'\n'}"    # If you need the line *without* newline
    else
        # Process line without newline
    fi
done

【讨论】:

  • 你很快!刚刚测试了while read line; do i=1; done &lt; &lt;(printf "one\ntwo\nthree"); [ -n "$line" ] &amp;&amp; echo "newline needed for $line" 并抬头看你打败了我:)
猜你喜欢
  • 2012-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-09
  • 1970-01-01
相关资源
最近更新 更多