简介
linux
中的换行符对于格式化文本输出、修改文件和确保跨系统兼容性至关重要。
linux
主要使用 lf
(换行符,\n
)来换行,而 windows
使用 crlf
(回车符 + 换行符,\r\n
)
检测文件中的换行符
使用 cat -a 查看换行符
cat -a myfile.txt
输出 linux
风格,lf \n
:
hello world$
输出 windows
风格,crlf \r\n
:
hello world^m$
$
:表示行的结束 (lf
)^m$
:表示文件有windows
换行符 (\r\n
)
使用 od -c 检查字符
od -c myfile.txt
输出:linux \n
0000000 h e l l o w o r l d \n
输出:windows \r\n
0000000 h e l l o w o r l d \r \n
\r \n
:windows
样式的行尾\n
:linux
风格的行尾
换行符格式转换
将 windows crlf (\r\n) 转换为 linux lf (\n)
- 使用
dos2unix
dos2unix myfile.txt
- 使用
sed
sed -i 's/\r$//' myfile.txt
- 使用
tr
cat myfile.txt | tr -d '\r' > newfile_unix.txt
将 linux lf (\n) 转换为 windows crlf (\r\n)
unix2dos
unix2dos myfile.txt
- 使用
sed
sed -i 's/$/\r/' myfile.txt
- 使用
awk
awk '{print $0 "\r"}' myfile.txt > newfile_windows.txt
在输出中添加换行符
打印多行文本
- 使用
echo -e
echo -e "line 1\nline 2\nline 3"
输出:
line 1 line 2 line 3
- 使用
printf
printf "line 1\nline 2\n"
在命令中插入换行符
使用 sed
echo "hello world" | sed 's/ / \n/g'
输出:
hello world
- 使用
awk
echo "hello world" | awk '{print $1 "\n" $2}'
处理 shell 脚本中的换行符
循环遍历文件中的行
#!/bin/bash while ifs= read -r line; do echo "processing: $line" done < myfile.txt
从文件中删除空行
sed -i '/^$/d' myfile.txt 或 awk 'nf' myfile.txt > clean_file.txt
计算文件中的换行符
grep -c '^' myfile.txt 或 wc -l myfile.txt
其他用法
用新行追加文本
echo "new entry" >> myfile.txt
追加到文本不添加新行
echo -n "new entry" >> myfile.txt
检查文件是否以新行结尾
tail -c1 myfile.txt | od -c
如果输出显示
\n
,则表示文件尾部有换行符。如果没有输出,则文件缺少尾随换行符。
使用多行字符串
将多行字符串分配给变量
mytext="line 1 line 2 line 3" echo "$mytext"
使用 cat 读取多行输入
cat <<eof > myfile.txt this is line 1. this is line 2. eof
在 linux 中处理 windows 格式的文件
修复文件中的 ^m 字符
- 使用
sed
sed -i 's/\r$//' myfile.txt
- 使用
vim
vim myfile.txt :set fileformat=unix :wq
以上就是linux换行符的使用方法详解的详细内容,更多关于linux换行符使用的资料请关注代码网其它相关文章!
发表评论