英文:
How to replace (space+newline) in SED
问题
我尝试了以下命令,但没有任何变化:
sed -i 's/[|\s^[[:space:]]*$]/|/g' tes.txt
以及:
sed -i 's/|\s\n/|/g' tes.txt
我想要将文本更改为如下所示:
jono|Jakarta|smp
jojon|jakarta|smp
jojo|bandung|sma
riki|Jakarta|smk
英文:
how to remove space and new line using sed
jono|(space)
(new line)
Jakarta|smp
jojon|jakarta|smp
jojo|bandung|sma
riki|(space)
(new line)
Jakarta|smk
i try this = sed -i 's/[|\s^[[:space:]]*$]/|/g' tes.txt
and this = sed -i 's/|\s\n/|/g' tes.txt
nothing has change
i want change to this
jono|Jakarta|smp
jojon|jakarta|smp
jojo|bandung|sma
riki|Jakarta|smk
答案1
得分: 0
"Materializing the comment by @Cyrus
>! sed -z 's/ \n//g' file
"
答案2
得分: 0
根据我们拥有的少量信息并从给定的格式推断,最安全的操作方式是:
$ sed 's/|/\n/g' file | sed '/^\s*$/d' | paste -sd '||\n'
这只是一个简单的转换,没有太多复杂操作:
- 将所有字段分隔符转换为换行符
- 删除所有只包含空格字符的行
- 将所有内容转换为3列
英文:
Based on the little information we have and extrapolating from the given format, the safest way to proceed would be:
$ sed 's/|/\n/g' file | sed '/^\s*$/d' | paste -sd '||\n'
This is just a straightforward transformation without a lot of fuzz:
- convert all the field separators into new lines
- delete all lines containing only space-characters
- convert everything into 3 columns
答案3
得分: 0
你可以匹配字符串末尾的|
后面跟着一个或多个空格。如果匹配成功,将下一行放入模式空间,并将|
后面的可选空格和换行符替换为单独的|
。
要替换所有匹配项,你可以使用类似于:a
的标签,然后使用ta
来测试分支。如果替换成功,则跳回到标签。
sed -E '/\|[[:space:]]+$/{:a;N;s/\|[[:space:]]*\n/|/;ta}' tes.txt
输出
jono|Jakarta|smp
jojon|jakarta|smp
jojo|bandung|sma
riki|Jakarta|smk
英文:
You could match |
followed by 1 or more spaces at the end of the string. If there is a match, take put the next line in the pattern space, and replace the |
followed by optional spaces and a newline with just |
To replace all occurrences, you could use a label like for example :a
and then use ta
to test the branch. If the replacement was successful, then jump back to the label.
sed -E '/\|[[:space:]]+$/{:a;N;s/\|[[:space:]]*\n/|/;ta}' tes.txt
Output
jono|Jakarta|smp
jojon|jakarta|smp
jojo|bandung|sma
riki|Jakarta|smk
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论