Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpret as fixed string/literal and not regex using sed

Tags:

unix

sed

For grep there's a fixed string option, -F (fgrep) to turn off regex interpretation of the search string. Is there a similar facility for sed? I couldn't find anything in the man. A recommendation of another gnu/linux tool would also be fine.

I'm using sed for the find and replace functionality: sed -i "s/abc/def/g"

like image 239
EoghanM Avatar asked Nov 09 '10 11:11

EoghanM


People also ask

Can you use regex with sed?

Although the simple searching and sorting can be performed using sed command, using regex with sed enables advanced level matching in text files. The regex works on the directions of characters used; these characters guide the sed command to perform the directed tasks.

Can you use sed on a string?

The sed command is a common Linux command-line text processing utility. It's pretty convenient to process text files using this command. However, sometimes, the text we want the sed command to process is not in a file. Instead, it can be a literal string or saved in a shell variable.

How do you escape the sed string?

In a nutshell, for sed 's/…/…/' : Write the regex between single quotes. Use '\'' to end up with a single quote in the regex. Put a backslash before $.


1 Answers

Do you have to use sed? If you're writing a bash script, you can do

#!/bin/bash  pattern='abc' replace='def' file=/path/to/file tmpfile="${TMPDIR:-/tmp}/$( basename "$file" ).$$"  while read -r line do   echo "${line//$pattern/$replace}" done < "$file" > "$tmpfile" && mv "$tmpfile" "$file" 

With an older Bourne shell (such as ksh88 or POSIX sh), you may not have that cool ${var/pattern/replace} structure, but you do have ${var#pattern} and ${var%pattern}, which can be used to split the string up and then reassemble it. If you need to do that, you're in for a lot more code - but it's really not too bad.

If you're not in a shell script already, you could pretty easily make the pattern, replace, and filename parameters and just call this. :)

PS: The ${TMPDIR:-/tmp} structure uses $TMPDIR if that's set in your environment, or uses /tmp if the variable isn't set. I like to stick the PID of the current process on the end of the filename in the hopes that it'll be slightly more unique. You should probably use mktemp or similar in the "real world", but this is ok for a quick example, and the mktemp binary isn't always available.

like image 103
dannysauer Avatar answered Nov 11 '22 22:11

dannysauer