vishwajeet_preeti
vishwajeet_preeti

Reputation: 5

Removing repeated characters with sed command

How to remove repeated characters or symbols in a string

some text\n\n\n some other text\n\n more text\n

How can I make something like this using sed or another command?

some text\n some other text\n more text\n

I can remove \n like sed s/\n//g but this will remove all the characters.

Upvotes: 0

Views: 448

Answers (3)

dawg
dawg

Reputation: 103874

Given the following [input] or a file that is similar:

printf "some text\n\n\n some other text\n\n more text\n" | [ one of the pipes below... ]

Any of these work:

[input] | sed -n '/[^[:space:]]/p'

Or:

[input] | sed '/^$/d'

Or, if you want to filter ^[spaces or tabs]\n also:

[input] | sed '/^[[:blank:]]*$/d'

Or with awk:

[input] | awk 'NF'

Upvotes: 0

Darkman
Darkman

Reputation: 2981

You can also use tr if it supports squeezings.

$ echo -e 'ab\n\ncd' | tr --squeeze-repeats '\n'
ab
cd

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626929

You can use

sed '/^$/d' file > newfile

In GNU sed, you can use inline replacement with -i option:

sed -i '/^$/d' file

In MacOS, FreeBSD sed inline replacement can be done with

sed -i '' '/^$/d' file
sed -i.bak '/^$/d' file

See the online demo:

#!/bin/bash
s=$(echo -e "some text\n\n\n some other text\n\n more text\n")
sed '/^$/d' <<< "$s"

Output:

some text
 some other text
 more text

Upvotes: 1

Related Questions