Home > System Tutorial > LINUX > body text

Summarized the method of removing newline characters in Linux

WBOY
Release: 2024-01-16 09:06:17
forward
1168 people have browsed it

今天需要删除文件里面的换行符,比如有一个文件a.txt:

1,2,3
4,5,6
1,2,3
4,5,6
1,2,3
4,5,6
1,2,3
4,5,6
1,2,3
4,5,6
Copy after login

1、使用vim删除换行符

vim输入命令:%s/\n//g

2、使用sed命令,例如 sed ':t;N;s/\n//;b t' a.txt

结果:1,2,34,5,61,2,34,5,61,2,34,5,61,2,34,5,61,2,34,5,6

解释一下:

:t 定义label "t"
b t 转到label "t" 继续执行
N 先读入一行到sed的模板空间,加个换行符(\n),再向sed模板空间追加下一行(之后sed 对模板空间中的内容执行s/\n/,/替换,并显示替换后的内容)
Copy after login

3、使用td命令,例如:

cat a.txt | tr '\n' ' ' 
1,2,3 4,5,6 1,2,3 4,5,6 1,2,3 4,5,6 1,2,3 4,5,6 1,2,3 4,5,6
Copy after login

注意tr最后那个参数是空格,否则会报错

Linux shell 中删除文件的所有换行符

需要做一个小功能,就是把一个文本文件中的所有换行符都去掉。一般肯定是想到使用sed来修改啦。但是我搜了一下,并没有找到sed要怎么输入\n——我知道^M对应的是\r,但是\n却失败了,在命令行中直接被切割掉。
  原则上可以用\015这样的方式来指定的,但是我实际操作发现并不行,没有效果。所以最终我只能用直接输入命令来做了(还没验证过写成脚本是否能用)。

假设要替换的文件叫做in.txt,输出文件为out.txt:

sed 's/^M//g' file.txt > tmp.txt
sed -i 's/\"/\\\"/g' tmp.txt
rm -f out.txt; touch out.txt
cat tmp.txt | xargs echo -n >> out.txt
rm -f tmp.txt
Copy after login

五个步骤分别为:

将Windows格式的换行转换成UNIX格式,也就是删除所有的\r字符。其中^M并不是直接输入这两个字符,而是通过在shell里面按住 Ctrl+V,然后再敲 M 得到的
将所有的双引号转义,因为后面的echo需要使用
创建一个全空的输出文件
删除所有的\n字符并输出最终文件
删除中间文件

The above is the detailed content of Summarized the method of removing newline characters in Linux. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!