使用 awk 打印文件而不添加尾随换行符
Print file without adding trailing newline with awk
我正在使用 awk 处理一些程序文件,删除调试部分。其中一些文件没有尾随换行符。我想让 awk 逐行打印文件,带换行符,但如果不存在则不在末尾添加额外的换行符。
例如
a
b // no newline after the "b"
正在变成这样:
a
b<NEWLINE>
我不想添加这个换行符的原因是我正在尝试使用 cmp --silent $file $file_without_debug_sections
来确定是使用原始文件还是新文件。我关心 that 的原因是我试图限制编译器输出中具有调试扩展名的文件数量。仅使用不同的非调试版本也可以清楚地知道此 "remove debug sections" 过程更改了哪些文件。
总而言之,我怎样才能让 awk 逐行浏览文件,但如果文件不存在则不在末尾添加换行符?
我当前的代码如下所示:
{
if ([=12=] ~ /^[ \t]*\/\/[ \t]*\/\*[ \t]*begin[ \t]+debug[ \t]*$/) {
print "/* begin debug";
} else if ([=12=] ~ /^[ \t]*\/\/[ \t]*end[\ t]+debug[\t ]*\*\/[ \t]*$/) {
print "end debug */";
} else print;
}
我尝试用 printf "%s", [=15=]
替换最后的 print
。但随后它从每一行中省略了一个换行符。
您可以简单地使用 awk
如果缺少换行符则在末尾附加换行符这一事实,如下所示:
# Let's say file1 does not contain a newline at the end. Since
# awk will add a newline at the end if it is missing, file1_debug
# WILL contain a newline at the end.
awk -f remove_debug.awk file1 > file1_debug
# Use awk again before comparing the files, this makes sure that when
# we compare them, both files have a newline at the end.
if cmp --silent <(awk '1' file1) <(awk '1' file1_debug) ; then
echo "The files are the same"
else
echo "The files differ"
fi
将您的 print line
语句更改为 printf "%s%s", line, RT
例如
$ seq 3 > s3
$ head -c -1 s3 > s3nn # remove last newline
$ awk '={printf "%s%s", [=10=], RT}' s3nn
1
2
3$ awk '=' s3nn
1
2
3
$ cat s3nn
1
2
3$
在你的例子中 print
没有参数等于 print [=14=]
我正在使用 awk 处理一些程序文件,删除调试部分。其中一些文件没有尾随换行符。我想让 awk 逐行打印文件,带换行符,但如果不存在则不在末尾添加额外的换行符。
例如
a
b // no newline after the "b"
正在变成这样:
a
b<NEWLINE>
我不想添加这个换行符的原因是我正在尝试使用 cmp --silent $file $file_without_debug_sections
来确定是使用原始文件还是新文件。我关心 that 的原因是我试图限制编译器输出中具有调试扩展名的文件数量。仅使用不同的非调试版本也可以清楚地知道此 "remove debug sections" 过程更改了哪些文件。
总而言之,我怎样才能让 awk 逐行浏览文件,但如果文件不存在则不在末尾添加换行符?
我当前的代码如下所示:
{
if ([=12=] ~ /^[ \t]*\/\/[ \t]*\/\*[ \t]*begin[ \t]+debug[ \t]*$/) {
print "/* begin debug";
} else if ([=12=] ~ /^[ \t]*\/\/[ \t]*end[\ t]+debug[\t ]*\*\/[ \t]*$/) {
print "end debug */";
} else print;
}
我尝试用 printf "%s", [=15=]
替换最后的 print
。但随后它从每一行中省略了一个换行符。
您可以简单地使用 awk
如果缺少换行符则在末尾附加换行符这一事实,如下所示:
# Let's say file1 does not contain a newline at the end. Since
# awk will add a newline at the end if it is missing, file1_debug
# WILL contain a newline at the end.
awk -f remove_debug.awk file1 > file1_debug
# Use awk again before comparing the files, this makes sure that when
# we compare them, both files have a newline at the end.
if cmp --silent <(awk '1' file1) <(awk '1' file1_debug) ; then
echo "The files are the same"
else
echo "The files differ"
fi
将您的 print line
语句更改为 printf "%s%s", line, RT
例如
$ seq 3 > s3
$ head -c -1 s3 > s3nn # remove last newline
$ awk '={printf "%s%s", [=10=], RT}' s3nn
1
2
3$ awk '=' s3nn
1
2
3
$ cat s3nn
1
2
3$
在你的例子中 print
没有参数等于 print [=14=]