gpt4 book ai didi

shell - awk/sed 替换换行符

转载 作者:行者123 更新时间:2023-12-04 23:40:51 24 4
gpt4 key购买 nike

介绍:

我得到了一个 CSV 文件,其中字段分隔符是管道字符(即 | )。
该文件具有预定义数量的字段(例如 N )。我可以发现 N 的值通过读取 CSV 文件的标题,我们可以假设它是正确的。

问题:

某些字段错误地包含换行符,这使得该行看起来比所需的短(即,它具有 M 字段,带有 M < N )。

我需要创建的是一个 sh脚本(不是 bash )来修复这些行。

尝试的解决方案:

我尝试创建以下脚本来尝试修复文件:

if [ $# -ne 1 ]
then
echo "Usage: $0 <filename>"
exit
fi

# get first line
first_line=$(head -n 1 $1)

# get number of fields
num_separators=$(echo "$first_line" | tr -d -c '|' | awk '{print length}')

cat $1 | awk -v numFields=$(( num_separators + 1 )) -F '|' '
{
totRecords = NF/numFields
# loop over lines
for (record=0; record < totRecords; record++) {
output = ""
# loop over fields
for (i=0; i<numFields; i++) {
j = (numFields*record)+i+1
# replace newline with question mark
sub("\n", "?", $j)
output = output (i > 0 ? "|" : "") $j
}
print output
}
}
'

但是,换行符仍然存在。
我该如何解决这个问题?

CSV 示例:
FIRST_NAME|LAST_NAME|NOTES
John|Smith|This is a field with a
newline
Foo|Bar|Baz

预期输出:
FIRST_NAME|LAST_NAME|NOTES
John|Smith|This is a field with a * newline
Foo|Bar|Baz

* I don't care about the replacement, it could be a space, a question mark, whatever except a newline or a pipe (which would create a new field)

最佳答案

$ cat tst.awk
BEGIN { FS=OFS="|" }
NR==1 { reqdNF = NF; printf "%s", $0; next }
{ printf "%s%s", (NF < reqdNF ? " " : ORS), $0 }
END { print "" }

$ awk -f tst.awk file.csv
FIRST_NAME|LAST_NAME|NOTES
John|Smith|This is a field with a newline
Foo|Bar|Baz

如果这不是您想要的,那么编辑您的问题以提供更真实的代表性样本输入和相关输出。

关于shell - awk/sed 替换换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38058997/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com