首页 > 解决方案 > 子字符串检测无法检测到换行符

问题描述

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

谷歌搜索,但没有任何工作。

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 等)。

我想:

情况1:

ip:

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

输出:

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

案例二:

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

对于这两种情况

标签: bashshellfileioscripting

解决方案


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

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

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

If you need to read through the lines, process them in the shell, and then output them with the missing newline added at the end, then just use your current loop, and output each line with a newline -- you need to add it whether or not it was there originally, and if you always add it, it'll always be there.

If you need to explicitly find out whether the last line had a newline and do something different if it did, one option is to modify your original code a little:

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

Another option is to read the entire file into an array (each line as an array entry), since mapfile doesn't remove the line terminators (unless you specifically ask it to with -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

推荐阅读