Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does \1 in sed do?

Tags:

sed

I found this question really relevant to what I wanted: Parsing using awk or sed in Unix, however I can't figure out what the following does:

's/\([,=]\) /\1/g'

I know that g does a global substitution but really can't understand what's going on within the context of the question.

like image 206
Abdullah Jibaly Avatar asked Jan 05 '11 22:01

Abdullah Jibaly


People also ask

What does sed '/ $/ D do?

It means that sed will read the next line and start processing it. nothing will be printed other than the blank lines, three times each. Show activity on this post. The command d is only applied to empty lines here: '/^$/d;p;p'.

What does the G in sed do?

In some versions of sed, the expression must be preceded by -e to indicate that an expression follows. The s stands for substitute, while the g stands for global, which means that all matching occurrences in the line would be replaced.

What is use of option's in sed command?

The syntax of the s command is ' s/ regexp / replacement / flags '. Its basic concept is simple: the s command attempts to match the pattern space against the supplied regular expression regexp ; if the match is successful, then that portion of the pattern space which was matched is replaced with replacement .

What is the P flag in sed?

The above sed command replaces the string only on the third line. Duplicating the replaced line with /p flag : The /p print flag prints the replaced line twice on the terminal. If a line does not have the search pattern and is not replaced, then the /p prints that line only once.


2 Answers

Here's a simple example:

$ echo 'abcabcabc' | sed 's/\(ab\)c/\1/' ababcabc $ echo 'abcabcabc' | sed 's/\(ab\)c/\1/g' ababab $ echo 'abcabcabc' | sed 's/\(ab\)\(c\)/\1d\2/g' abdcabdcabdc 

In the first command, only the first match is affected. In the second command, every match is affected. In both cases, the \1 refers to the characters captured by the escaped parentheses.

In the third command, two capture groups are specified. They are referred to by using \1 and \2. Up to nine capture groups can be used.

In addition to the g (global) operator (or without it, the first match), you can specify a particular match:

$ echo 'aaaaaa' | sed 's/a/A/4' aaaAaa 
like image 101
Dennis Williamson Avatar answered Oct 06 '22 22:10

Dennis Williamson


\(...\) would capture the characters specified inside of the parens and \1 would be used to reference the first match, this is a part of regex.

like image 39
meder omuraliev Avatar answered Oct 06 '22 21:10

meder omuraliev