3

Given this example of a text file containing only some usernames separated by lines:

@Alice @Bob Cindy Leon @Mark 

How can I add @ to the beginning of every line that doesn't have it already?

1 Answer 1

7

Statements in sed scripts have a [address[,address]][!] action pattern, where address can be a line number or /regexp/ and the address(es) can be reversed with ! (not), so here you'd write:

sed '/^@/! s/^/@/' < file 

To add a @ to the start of lines that don't already have one.

The address is /^@/ (lines with @ following the start of the line (^)), ! reverses it so that the s/^/@/ action (substitute the start of the line with @) is only run on the lines that don't match.

You can achieve the same effect with:

sed 's/^@\{0,1\}/@/' < file 

Which replaces 0 or 1 @ at the start with @. Same with EREs:

sed -E 's/^@?/@/' < file 
3
  • Thank you. Is it a kind of "if" in the first command? Why separated by a space? Commented Nov 18, 2022 at 17:44
  • 1
    @SeppA see edit. Commented Nov 18, 2022 at 17:50
  • 1
    @Quasímodo, yes, though that wouldn't insert a @ if the first bytes of the line could not be decoded into a character in the locale (like on the output of printf '\311ric\n' (the iso8859-1 encoding of Éric) if run in a locale that uses UTF-8 (in any case the behaviour of sed is unspecified on non-text input). That would also not add a @ at the start of empty line (which may or may not be better). Commented Nov 19, 2022 at 14:04

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.