sed

By Druss , 6 July, 2015

If you see something like the following error message when you run a sed command:

invalid reference \1 on `s' command's RHS

then it (probably) means that your regex capture group has not been escaped properly.

So, if you are using a command like:

sed "s/foo(bar)[123]/baz\1/"

then it needs to be escaped like so:

sed "s/foo\(bar\)[123]/baz\1/"

In other words, round parentheses/brackets need to be escaped while the square brackets do not :|

Hope this helps :)

By Druss , 2 May, 2013

In Linux, replacing all instances of a string with another string is easy thanks to sed. A simple example is as follows:

To replace the string foo with the string bar in all .txt files:

sed 's#foo#bar#g' *.txt

This will replace the strings. However, it won't actually save the changes and will instead output the modified text to the screen. To retain the changes or, in other words, to perform the replacements in place within the file, use the -i switch:

Tags Old
By Druss , 27 January, 2012

Today, I made quite an impression on my furniture thanks to incessant contact between it and my illustrious head. This, as usual, was due to my looking for a clean regex to solve my issue while working with text files in Vim. My task was, I initially believed, quite simple: delete all the lines that are sandwiched between two types/patterns of lines. In this case, the top slice of the sandwich consisted of a line which was entirely a number and the bottom slice was a line entirely populated with underscores.

By Druss , 30 July, 2011

I've previously written a short tip on how to perform batch rename operations using ls, sed, and xargs. One of the issues with xargs is that it breaks down when dealing with filenames which include spaces as it assumes that each word in the filename is a separate argument. Looking around on the Internet threw up a number of solutions mostly utilising find and xargs with the -print0 and -0 switches respectively.

Tags Old
By Druss , 24 January, 2011

Earlier today, I wanted to prefix a number of image files on a server with a 0. If this was on my desktop, I would have simply used a graphical tool such as the excellent Métamorphose. However, in this case, only a command-line was available. While Google threw up a number of bash scripts, I was curious to see if this could be done in a cleaner and more concise manner. Following the excellent reference to sed and more Google magicking, I arrived at

Tags Old

All times are UTC. All content licensed under the Creative Commons Attribution-Noncommercial-Share Alike 3.0 License.