如何在SED中替换(空格+换行符)

huangapple go评论69阅读模式
英文:

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"

英文:

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

Sed demo

huangapple
  • 本文由 发表于 2023年6月30日 02:17:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76583677.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定